我需要使用PHP按键值对数组进行排序。
我正在解释下面的数组。
$clients=array(array("clinet_id"=>9,"company"=>3,"id"=>4),array("clinet_id"=>9,"company"=>3,"id"=>6),array("clinet_id"=>9,"company"=>3,"id"=>7),array("clinet_id"=>10,"company"=>2,"id"=>4),array("clinet_id"=>10,"company"=>2,"id"=>8));
echo json_encode($clients);
这里我需要按照client_id
排序数组,这意味着同一client_id
将合并为一个数组,其中id
为逗号分隔字符串。我正在解释下面的预期输出。
$templatearr[9]=array('3' =>4,6,7)
$templatearr[10]=array('2' =>4,8)
这意味着它应该是$templatearr[clinet_id]=array(company =>id1,id2,...,)
格式。
答案 0 :(得分:1)
只需使用foreach
和Build
新数组,如下所示
<?php
$clients=array(array("clinet_id"=>9,"company"=>3,"id"=>4),array("clinet_id"=>9,"company"=>3,"id"=>6),array("clinet_id"=>9,"company"=>3,"id"=>7),array("clinet_id"=>10,"company"=>2,"id"=>4),array("clinet_id"=>10,"company"=>2,"id"=>8));
$temp =array();
foreach($clients as $key=>$val)
{
if(isset($temp[$val['clinet_id']])){
$temp[$val['clinet_id']][$val['company']].=','.$val['id'];
}else{
$temp[$val['clinet_id']][$val['company']]=$val['id'];
}
}
print_r($temp);
?>
输出
Array
(
[9] => Array
(
[3] => 4,6,7
)
[10] => Array
(
[2] => 4,8
)
)
答案 1 :(得分:1)
$tmp = array();
foreach ($clients as $k => $v) {
if(!isset($tmp[$v['clinet_id']])){
$tmp[$v['clinet_id']] = '';
}
if(!is_array($tmp[$v['clinet_id']])){
$tmp[$v['clinet_id']][$v['company']] = strval($v['id']);
}else{
if($tmp[$v['clinet_id']][$v['company']]){
$tmp[$v['clinet_id']][$v['company']] .=','.$v['id'];
}else{
$tmp[$v['clinet_id']][$v['company']] = strval($v['id']);
}
}
}
结果是:
Array
(
[9] => Array
(
[3] => 4,6,7
)
[10] => Array
(
[2] => 4,8
)
)