PHP多维数组循环和按​​值分组

时间:2016-03-04 15:33:44

标签: php arrays loops multidimensional-array

我有一个多维数组,如下所示:

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 " ????? ";
}

非常感谢!

2 个答案:

答案 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;
        }
    }
    }