Thursday 6 September 2018

PHP: How to access the values of the array elements using the array index

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?

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

?>

0 comments:

Post a Comment