我有一个多维数组,如下所示:
Array (
[0] => Array ( [A] => Apple )
[1] => Array ( [A] => Banana )
[2] => Array ( [A] => Strawberry )
[3] => Array ( [B] => Computer )
)
现在我想循环遍历该数组并输出按[A],[B],...分组的值 但就我而言,我不知道是否有[A],[B]或[C]。
结果应如下所示:
[A] Apple, Banana, Strawberry
[B] Computer
到目前为止,这是我的代码:
$service_links[] = array();
$sl_i = 0;
if( have_rows('services') ):
// loop through the rows of data
while ( have_rows('services') ) : the_row();
if( get_row_layout() == 'service_category' ) {
$service_category_taxonomy = get_sub_field('service_category_taxonomy');
$service_links[$sl_i][$service_category_taxonomy] = get_sub_field('service_group_title');
$sl_i++;
}
endwhile;
endif;
foreach ( $service_links as $var ) {
echo " ????? ";
}
非常感谢!
答案 0 :(得分:2)
我会用foreach
:
$array = ''; //<-- This is your array
$final = [];
foreach ($array as $a) {
foreach ($a as $k => $v) {
$final[$k][] = $v;
}
}
var_dump($final);
<强>结果:强>
array (size=2)
'A' =>
array (size=3)
0 => string 'Apple' (length=5)
1 => string 'Banana' (length=6)
2 => string 'Strawberry' (length=10)
'B' =>
array (size=1)
0 => string 'Computer' (length=8)
您稍后可以使用implode
以逗号分隔结果:
echo implode(',', $final['A']); // OUTPUT: Apple,Banana,Strawberry
答案 1 :(得分:1)
这样的事情:
$results = array();
foreach($arr as $a){
foreach($a as $key=>$value){
if(array_key_exists($key,$results)){
$results[$key]=$results[$key].",".$value;
}else{
$results[$key] = $value;
}
}
}