2 回答
TA贡献1786条经验 获得超11个赞
$src = array(
array(
"uid" => "29",
"title" => "Developer",
"city" => "Madrid"
),
array(
"uid" => "29",
"title" => "Developer",
"city" => "Berlin"
),
array(
"uid" => "29",
"title" => "Developer",
"city" => "London"
),
array(
"uid" => "30",
"title" => "Designer",
"city" => "Amsterdam"
),
);
/* placeholder for storing final array */
$out=array();
/* iterate through source array */
foreach( $src as $arr ){
/* for convenience, cast child array as object */
$obj=(object)$arr;
$key=$obj->uid;
/* construct outpur array format & add values from child arrays/objects */
if( !array_key_exists( $key, $out ) )$out[ $key ]=array();
if( !array_key_exists( 'title', $out[ $key ] ) )$out[ $key ]['title']=$obj->title;
if( !array_key_exists( 'city', $out[ $key ] ) ) $out[ $key ]['city']=array();
$out[ $key ]['city'][]=$obj->city;
}
/* this produces an output array keyed by uid */
printf('<pre>%s</pre>',print_r($out,true));
/* If the uid keys are not important and should not appear in output */
$final=array();
foreach( $out as $uid => $child )$final[]=$child;
printf('<pre>%s</pre>',print_r($final,true));
其输出为:
Array
(
[29] => Array
(
[title] => Developer
[city] => Array
(
[0] => Madrid
[1] => Berlin
[2] => London
)
)
[30] => Array
(
[title] => Designer
[city] => Array
(
[0] => Amsterdam
)
)
)
Array
(
[0] => Array
(
[title] => Developer
[city] => Array
(
[0] => Madrid
[1] => Berlin
[2] => London
)
)
[1] => Array
(
[title] => Designer
[city] => Array
(
[0] => Amsterdam
)
)
)
TA贡献1828条经验 获得超13个赞
这可能是您正在寻找的内容:
<?php
$input = [
[
"uid" => "29",
"title" => "Developer",
"city" => "Madrid"
],
[
"uid" => "29",
"title" => "Developer",
"city" => "Berlin"
],
[
"uid" => "29",
"title" => "Developer",
"city" => "London"
],
[
"uid" => "30",
"title" => "Designer",
"city" => "Amsterdam"
]
];
$output = [];
array_walk($input, function($entry) use (&$output) {
if (!array_key_exists($entry["uid"], $output)) {
$output[$entry["uid"]] = [
"title" => $entry["title"],
"city" => [$entry["city"]]
];
} else {
$output[$entry["uid"]]["city"][] = $entry["city"];
}
});
var_dump($output);
输出显然是:
array(2) {
[29]=>
array(2) {
["title"]=>
string(9) "Developer"
["city"]=>
array(3) {
[0]=>
string(6) "Madrid"
[1]=>
string(6) "Berlin"
[2]=>
string(6) "London"
}
}
[30]=>
array(2) {
["title"]=>
string(8) "Designer"
["city"]=>
array(1) {
[0]=>
string(9) "Amsterdam"
}
}
}
- 2 回答
- 0 关注
- 184 浏览
添加回答
举报