2
$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()?

4
  • Using javascript I suppose? Commented Jan 9, 2014 at 12:28
  • Why can't you just read it from $array? It's unclear what your actual problem is Commented Jan 9, 2014 at 12:29
  • Get what you want and then encode it. Commented Jan 9, 2014 at 12:29
  • put values in different arrays and encode them. For eg: echo json_encode($array['Inter']); Commented Jan 9, 2014 at 12:29

2 Answers 2

2

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']);
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

So what do you need for it. Just echo it and that`s all. You can add die after echo to ensure that nothing else will not outputed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.