After several attempts, I have to ask for some help to solve this. Below I have some plain JSON:
{
"test": {
"r1": [{
"id": 1,
"status": true
}, {
"id": 2,
"status": true
}],
"r2": [{
"id": 1,
"status": false
}, {
"id": 2,
"status": false
}]
}
}
This works fine with javascript when I'm reading from a simple .txt file, but I want to create this JSON from PHP. I can make a two dimensional associative array, but for this it seems that I need a three dimensional associative array, and I can't solve that! Could someone give me a hint how that would look or alternative solutions?
Here's an embracing example with your data on how to convert from JSON object (string) to PHP array and vice-versa.
Hope this makes things clear for you.
<?php
// Original JSON object string
$jsonstring = '{
"test":{
"r1":[{
"id":1,
"status":true
},{
"id":2,
"status":true
}],
"r2":[{
"id":1,
"status":false
},{
"id":2,
"status":false
}]
}
}';
// Convert JSON string to PHP array
// This can be used by a PHP script to work on
$phparray = json_decode($jsonstring);
echo '<h3>PHP array converted from JSON string</h3><pre>'; var_dump($phparray); echo '</pre>';
// Convert it back to JSON string to prove it's the same
$jsonstring1 = json_encode($phparray);
// Now we create a PHP array corresponding to original JSON string, manually
$phparray = array (
"test"=> array (
"r1" => array(
array(
"id"=>1,
"status"=>true
),
array(
"id"=>2,
"status"=>true
)
),
"r2" => array(
array(
"id"=>1,
"status"=>false
),
array(
"id"=>2,
"status"=>false
)
)
)
);
// Convert PHP array to JSON string
// This can be sent to a browser where it can be used by Javascript
$jsonstring2 = json_encode($phparray);
echo '<h3>Original JSON string</h3>' . $jsonstring;
echo '<h3>After conversion to array and back</h3>' . $jsonstring1;
echo '<h3>Converted from PHP array</h3>' . $jsonstring2;
?>