MacMan
MacMan

Reputation: 933

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.

Upvotes: -1

Views: 47

Answers (2)

mickmackusa
mickmackusa

Reputation: 47894

That is a seriously odd/unwieldy data structure. Assuming that there will only be a count and an indexed element on the first level, you can search the second level for indexed elements and use those values as the keys of values of relevance.

Code: (Demo)

$result = [];
foreach ($array[0] as $k => $v) {
    if (is_int($k)) {
        $result[$v] = $array[0][$v][0];
    }
}
var_export($result);

Output:

array (
  'name' => 'mac',
  'staffid' => '1234',
  'school' => 'western',
)

Upvotes: 0

Marcus
Marcus

Reputation: 1930

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]]);
    }
}

Upvotes: 2

Related Questions