简体   繁体   中英

PHP Multidimensional Array loop and group by value

I have a multidimensional array that looks like this:

Array ( 
 [0] => Array ( [A] => Apple ) 
 [1] => Array ( [A] => Banana ) 
 [2] => Array ( [A] => Strawberry ) 
 [3] => Array ( [B] => Computer ) 
) 

Now i would like to loop through that array and output the values grouped by [A],[B], … But in my case I don't know if there is an [A], [B] or [C].

The Result should look like this:

[A] Apple, Banana, Strawberry
[B] Computer

This is my code so far:

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

Thank you very much!

I would loop it with a foreach :

$array = ''; //<-- This is your array

$final = [];
foreach ($array as $a) {
    foreach ($a as $k => $v) {
        $final[$k][] = $v;
    }
}
var_dump($final);

Result:

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)

You can later use implode to make your results comma delimited:

echo implode(',', $final['A']); // OUTPUT: Apple,Banana,Strawberry

Something like this :

$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;
        }
    }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM