user3116334
user3116334

Reputation: 63

json_encode particular part of array

$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:

  1. For Inter:

    echo $array['Inter'];
    
  2. For Real:

    foreach($array["Real"] as $real){ 
        echo $real."<br>";
    }
    

How can I do the same with json_encode()?

Upvotes: 2

Views: 597

Answers (2)

Spell
Spell

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

Justinas
Justinas

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

Related Questions