Highdel Highdel - 3 years ago 93
JSON Question

Dynamically creating multidimensional arrays to be encoded into JSON

I have a section of an array defined:

$arrData['categories'] = array();
array_push($arrData['categories'],array("category" => array(array("label"=>"Beef"),array("label"=>"Chicken"))));
array_push($arrDAta['categories'][0]['category'],array("label"=>"pork"));


The arrays are nested so that it encodes into JSON properly with all the {[{[{[]}]}]} formatted properly.

However, I need to create these types of meats dynamically, not statically. When I try to add onto the array in the third line of code to simulate dynamic creation, it throws an error:


Warning: array_push() expects parameter 1 to be an array, null given


Well,
$arrData['categories'][0]['category]
IS an array, so why does it shoot me down?

To show myself that I'm not crazy, I var_dump
$arrData['categories'][0]['category']
and get an array of size 1:

array (size=1)
'category' =>
array (size=2)
0 =>
array (size=1)
'label' => string 'Beef' (length=4)
1 =>
array (size=1)
'label' => string 'Chicken' (length=7)

Answer Source

Its the capitalization. In the third line the variable $arrDAta is capitalized differently than the others ($arrData)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download