Hertus Hertus - 6 months ago 17
PHP Question

Echo Multidimensional array

My array:

$array = array('name'=>'test','server'=>'zangarmarsh','fields'=>'items,stats');
$type = 'character';
$r = $client->fetch($type,$array);
echo '<pre>';
print_r($r);
echo '</pre>';


The output which I get out of the array:

Array
(
[result] => Array
(
[lastModified] => 1464923915000

[items] => Array
(
[averageItemLevel] => 710

[head] => Array
(
[id] => 125899

[tooltipParams] => Array
(
[transmogItem] => 71356

)

[bonusLists] => Array
(
)
)

[neck] => Array
(
[id] => 127976

[tooltipParams] => Array
(

[upgrade] => Array
(

[itemLevelIncrement] => 0
)

[timewalkerLevel] => 100
)


I know i need to use foreach, but i´m a bit overtaxed. If I use this i get the output of the [result] array, but how can i get the informations out of the other ones.

foreach ($r as $v1) {
foreach ($v1 as $v2) {
echo "$v2\n";
}
}

Answer

It depends on what you want to achieve. For example if you always have the same result structure: with a entry "result" and inside "result" a "modified" entry and any number of items, and you want to access the items you can do something like this:

$items = $r['result']['items'];
echo 'averageItemLevel: '.$items['averageItemLevel'].'\n';
echo 'head_id: '.$items['head']['id'].'\n';
foreach($items['head']['tooltipParams'] as $key => $value){
    echo 'head_'.$key.': '.$value.'\n';
}