2

How to access array element values using array-index?

<?
$json = '{
    "dynamic":{
       "pageCount":"12",
       "tableCount":"1"
    }
}';

$arr = json_decode($json, true);

echo $arr['dynamic']['pageCount']; // working
echo $arr[0]['pageCount']; // not working
?>

I will not know what is there in 'dynamic', so i want to access pageCount values dynamically?

Shiv
  • 1,211
  • 4
  • 14
  • 24
  • 1
    `foreach` will iterate over the array, providing both keys and values. `reset` will return the first value regardless of key (you can also get the key with `key`). `array_values` will replace the keys with auto-incrementing integers. What exactly is your use case? – Jon Sep 05 '12 at 08:24

2 Answers2

14

array_values is function you are looking for

Examples:

<?php
$json = '{
    "dynamic":{
       "pageCount":"12",
       "tableCount":"1"
    }
}';

$arr = json_decode($json, true);
echo $arr['dynamic']['pageCount']; // working

$arr = array_values($arr);
echo $arr[0]['pageCount']; // NOW working

?>
1
$arr = json_decode($json, true);
foreach ($arr as $key => $value) {
    if (isset($value['pageCount'])) {
        //do something with the page count
    }
}

If the structure is always a single nested JS object:

$obj = current($arr);
echo $obj['pageCount'];
Dan Grossman
  • 51,866
  • 10
  • 112
  • 101
  • OK, got it working. But was thinking if there is direct access without loops – Shiv Sep 05 '12 at 08:32
  • @ShivaramAllva: It can be so direct that it hurts: `extract(reset($arr));`. As I said in the comment -- what's the use case? – Jon Sep 05 '12 at 08:35
  • I have updated my answer with a non-looping solution that will work only if the structure is always a single nested JS object as in the example. – Dan Grossman Sep 05 '12 at 08:36