phparraysmultidimensional-arrayassociative-array

Isolate relevant multidimensional array data as a flat associative array


I have an array like the following. This is the results of a query on one of our servers.

[
    'count' => 1,
    [
        'name' => ['count' => 1, 'mac'],
        'name',
        'staffid' => ['count' => 1, '1234'],
        'staffid',
        'school' => ['count' => 1, 'western'],
        'school',
        'count' => 3,
        'dn' => 'cn=mac,cn=staff',
    ],
]

How do I loop through this array and create a new array as follows.

Array
(
    [name] => mac
    [staffid] => 1234
    [school] => western
)

I've tried a foreach loop echoing the key & values, but I'm not sure where to go from there. There will be more results returned as the query is expanded, but original array layout will be the same and the new layout needs to be the same format.


Solution

  • Try this:

    $result = array();
    foreach($yourArray as $element){
        for($i=0;$i<$element['count']; $i++){
            unset($element[$element[$i]]['count']);
            $result[$element[$i]] = implode(', ', $element[$element[$i]]);
        }
    }