Reputation: 63
$array = array("Real" => array("Alonso","Zidan"),"Inter" => "Zanetti", "Roma" => "Toti");
$json=json_encode($array);
echo $json
By this way I am reading all the data, but how can I read the data of
only Real
or Inter
?
For example, if it is json_decoded I can do so:
For Inter
:
echo $array['Inter'];
For Real
:
foreach($array["Real"] as $real){
echo $real."<br>";
}
How can I do the same with json_encode()
?
Upvotes: 2
Views: 597
Reputation: 8658
As I understand your question you need to output the json`d object.
Input
$input = '{"Real":["Alonso","Zidan"],"Inter":"Zanetti","Roma":"Toti"}';
In php:
// Second true is for array return, not object)
$string = json_decode($input, true)
echo $string['Inter'];
In Javascript (jQuery):
var obj = jQuery.parseJSON(input);
if (obj != undefined) {
echo obj['Inter'];
}
UPD:
If you need to get an json in all arrays you need to make follow:
$array = array("Real" => array("Alonso","Zidan"),"Inter" => "Zanetti", "Roma" => "Toti");
foreach($array as $key => $value) {
$array[$key] = json_encode($value);
}
After this code all variables in array will be json`ed and you can echo them in any time
Upvotes: 0
Reputation: 43507
json_encode()
returns a string, so you can't access its parts without parsing the string. But you can do the following instead:
echo json_encode($array['Inter']);
Upvotes: 2