Darshan Darshan - 9 months ago 45
JSON Question

Getting the array index key to variable - 2D PHP array

I have searched for many places for an answer I couldn't find one, so please help me sort out this. - Thanks in Advanced.

1.I have an Json String


2.which has been decoded and that has been saved in an php array

$arr = json_decode($json, true);

3.Now I tried to obtain those first, second, etc... values to concatenate with an sql query, but I couldn't get this sorted, so far I have tried like below,

foreach ($arr as $assoc) {
foreach ($assoc as $value) {


$sqlI = "UPDATE tblName SET fieldName = ".$val." WHERE fieldName1=".$assoc;

*note: the fieldName1 will have unique values..

I am getting Notice: Array to string conversion error I understand this due to $assoc is an array type but how to get the key from this array?


Your array would look like this:

$arr = Array(
   'first' => array(
       'val' => 100
   'second' => array(
       'val' => 200
   'thirth' => array(
       'val' => 300

You can access them like so:

echo $arr['first']['val']; // 100

Loop trough them like so:

foreach($arr as $val){
    echo $val['val']; // 100, 200, 300.

Or with key:

foreach($arr as $key => $val){
    echo "current key: '$key' with val '". $val['val'] ."'";