This is the code for grouping elements in array by specific key field of the element.
The result is below.
Code
<?php function groupBySpecificKey(array& $source, $key){ $map = array(); foreach($source as $elem){ $groupKey = $elem[$key]; if(is_null($groupKey)) continue; $map[$groupKey][] = $elem; } return $map; }
Example
$result = groupBySpecificKey($source, 'country'); var_dump($result); $source = array( array('id' => 1, 'name' =>'Joe', 'country' => 'China'), array('id' => 2, 'name' =>'Chris', 'country' => 'USA'), array('id' => 3, 'name' =>'Tod', 'country' => 'USA'), );
The result is below.
array(2) { ["China"]=> array(1) { [0]=> array(3) { ["id"]=> int(1) ["name"]=> string(3) "Joe" ["country"]=> string(5) "China" } } ["USA"]=> array(2) { [0]=> array(3) { ["id"]=> int(2) ["name"]=> string(5) "Chris" ["country"]=> string(3) "USA" } [1]=> array(3) { ["id"]=> int(3) ["name"]=> string(4) "Tod" ["country"]=> string(3) "USA" } } }
コメント