请帮助我下面的问题:
我有三个数组:
array(3) {
[0]=>
array(2) {
["name"]=>string(1) "A",
["location"]=>string(9) "first loc"
}
[1]=>
array(2) {
["name"]=>string(1) "A",
["location"]=>string(9) "second loc"
}
[2]=>
array(2) {
["name"]=>string(1) "B",
["location"]=>string(9) "third loc"
}
}
前两个数组具有相同的键和值。
请帮助我创建一个新的PHP数组从上面三个如下:
array(2) {
[0] =>
array(1) {
["A"] =>
array(2) {
[0]=> string(9) "first loc",
[1]=> string(9) "second loc"
}
},
[1] =>
array(1) {
["B"] =>
array(1) {
[0]=> string(9) "third loc"
}
}
}
try this
<?php
// sample data to work on
$a = array(
0=> array(
"name"=> "A",
"location"=>"0 loc"
),
1=> array(
"name"=> "A",
"location"=>"1 loc"
),
2=> array(
"name"=>"B",
"location"=>"2 loc"
),
3=> array(
"name"=>"B",
"location"=>"3 loc"
),
4=> array(
"name"=>"A",
"location"=>"4 loc"
),
5=> array(
"name"=>"B",
"location"=>"5 loc"
)
);
echo '<pre>';
$b = array();
foreach($a as $v) {
if( isset( $b[ $v['name'] ] )) {
// If 'A', 'B', .. so on key already exist, push this item's location
array_push( $b[ $v['name'] ], $v['location'] ) ;
} else {
// Create new key
$b[ $v['name'] ] = array($v['location']);
}
}
print_r($b);
?>
输出:Array
(
[A] => Array
(
[0] => 0 loc
[1] => 1 loc
[2] => 4 loc
)
[B] => Array
(
[0] => 2 loc
[1] => 3 loc
[2] => 5 loc
)
)