Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
    
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 5 '12 at 8:24

3 Answers 3

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

?>
share|improve this answer
$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'];
share|improve this answer
    
OK, got it working. But was thinking if there is direct access without loops –  Shivaram Allva Sep 5 '12 at 8: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 5 '12 at 8: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 5 '12 at 8:36

You can loop through the array, and check the array keys:

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

$arr = json_decode($json, true);
foreach($arr as $key => $value) {
  if( $key == 'dynamic' && is_array($value) ) {
    foreach($value as $subkey => $subvalue) {
      // do your thing
    }
  }
}
share|improve this answer
1  
The whole point of the question is that the specific key "dynamic" is unknown. –  Jon Sep 5 '12 at 8:27

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.