Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How to access array element values using array-index [duplicate]

Tags:

arrays

php

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?

like image 980
Shiv Avatar asked Feb 17 '26 13:02

Shiv


2 Answers

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

?>
like image 82
Tufan Barış Yıldırım Avatar answered Feb 19 '26 03:02

Tufan Barış Yıldırım


$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'];
like image 27
Dan Grossman Avatar answered Feb 19 '26 04:02

Dan Grossman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!