Home > Software engineering >  Group values in multi-dimensional array based on a key
Group values in multi-dimensional array based on a key

Time:10-13

I have the following multi-dimensional array:

Array
(
    [0] => Array
        (
        [sname] => florida
        [cname] => orlando
        )

    [1] => Array
        (
        [sname] => texas
        [cname] => dallas
        )

    [2] => Array
        (
        [sname] => florida
        [cname] => tampa
        )

    [3] => Array
        (
        [sname] => ohio
        [cname] => columbus
        )

)

How would I go about trying to get all 'cname' values associated with each 'sname' value?

florida:    orlando, tampa
texas:      dallas
ohio:       columbus

CodePudding user response:

With a slight tweak of Mike's solution (https://stackoverflow.com/a/2189916/4954574), the following will produce what I was hoping for:

$input_arr = array(
    array("sname" => "florida", "cname" => "orlando"),
    array("sname" => "texas", "cname" => "dallas"),
    array("sname" => "florida", "cname" => "tampa"),
    array("sname" => "ohio", "cname" => "columbus")
);

foreach ($input_arr as $key => &$entry) {
    $level_arr[$entry['sname']][$key] = $entry['cname'];
}

print_r($level_arr);

Output:

Array
(
    [florida] => Array
        (
            [0] => orlando
            [2] => tampa
        )

    [texas] => Array
        (
            [1] => dallas
        )

    [ohio] => Array
        (
            [3] => columbus
        )

)

I am new with PHP arrays, so I'm not certain if this is the most efficient way or not?

CodePudding user response:

There are probably several ways to do this. The one that comes to mind is something like this:

<?php

$payload = [];
$origin = [
    [
        'sname' => 'florida',
        'cname' => 'orlando'
    ],
    [
        'sname' => 'texas',
        'cname' => 'dallas'
    ],
    [
        'sname' => 'florida',
        'cname' => 'tampa'
    ],
    [
        'sname' => 'ohio',
        'cname' => 'columbus'
    ]
];


foreach ($origin as $value) {
  if (! isset($payload[$value['sname']])) {
    $payload[$value['sname']] = '';
  }

  $payload[$value['sname']] .= (strlen($payload[$value['sname']]) >0?',':'') . $value['cname'];
}

print_r($payload);

Cheers! :)

=C=

  • Related