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?

1
  • 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? Commented Sep 5, 2012 at 8:24

2 Answers 2

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

?>
Sign up to request clarification or add additional context in comments.

Comments

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'];

3 Comments

OK, got it working. But was thinking if there is direct access without loops
@ShivaramAllva: It can be so direct that it hurts: extract(reset($arr));. As I said in the comment -- what's the use case?
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.