0

I tried this code

$jsonlogcontents='{"buildings":"townhall","Army":{ "Paladins":{ "325648":0, "546545":4 }, "Knights":{ "325648":-2, "546545":0 } } }';
$phpArray = json_decode($jsonlogcontents, false);
echo $phpArray->buildings;
echo $phpArray->Army;

This is just a sample of my code, the JSON file is too large to include and has sensitive information. The problem I'm having is I can't get the value or print the value of

$phpArray->Army

It give's me an error. I can however print or get the value of

$phpArray->buildings

I'm thinking that when you decode a JSON file/contents in PHP, you can't get/print/store the value of a 'key' that has more set of info (more { and }) or brackets in it. You can only print/get values for keys who's value's contain only 1 value and nothing else.

If this is the case, what can I do to get the contents of the key that has more JSON codes in it. Also, how can I convert the contents of a key that has more JSON info in it into a string? the conversion is so I can display the value of that key to the page or echo it

  • 1
    how are you printing? try `var_dump($phpArray->Army)` – serakfalcon May 11 '14 at 16:27
  • 1
    what says `print_r` or `var_dump`? – Adrian Preuss May 11 '14 at 16:27
  • Actually I just do `echo $phpArray->Army;`. I am going to save each data to mysql database like Buildings and Army. For Army however, I will need to do another json_decode() for that. The complication is the code will actually not be able to tell which has valid values and which has more JSON codes in their values. So I need to make a code that will check if a value has valid info. Alternatively, I can just force each values into string type so I can save them to database or print them exactly as JSON code in string – user3613603 May 11 '14 at 16:34

3 Answers3

0

When you are adding false as the second parameter to the json_encode it will updating all array to the sdClass empty objects.In this way you can the main array as the object

<?php

$json = '{
    "buildings": "townhall",
    "Army": {
        "Paladins": {
            "325648": 0,
            "546545": 4
        },
        "Knights": {
            "325648": -2,
            "546545": 0
        }
    }
}';

$array = json_decode($json, true);
$object = (object)$array;

var_dump($object->Army);


?>

OUTPUT

array(2) {
  ["Paladins"]=>
  array(2) {
    [325648]=>
    int(0)
    [546545]=>
    int(4)
  }
  ["Knights"]=>
  array(2) {
    [325648]=>
    int(-2)
    [546545]=>
    int(0)
  }
}

Working Demo

underscore
  • 6,495
  • 6
  • 39
  • 78
  • ah this answers my question on top :) – user3613603 May 11 '14 at 16:43
  • 1
    "When you are adding false as the second parameter to the json_encode it will updating all array to the sdClass empty objects." They're not empty at all. "In this way you can the main array as the object" This doesn't help. Whether you decode it as an array or as an object doesn't solve the particular problem in the question of how to display it. Decoding it as an array only makes the syntax for accessing the data more complicated, and the `(object)` cast is simply an anti-pattern. – Boann May 11 '14 at 16:47
  • can't accept it yet, I'm juggling all your answers coz I'm still stuck with an issue. Hold on a few minutes more – user3613603 May 11 '14 at 16:58
0

The error is because Army is an object, and echo doesn't know how to convert it to a string for display. Use:

print_r($phpArray->Army);

or:

var_dump($phpArray->Army);

to see its contents.

P.S. $phpArray not an array but an object.

For Army however, I will need to do another json_decode() for that.

You don't. json_decode() decodes the entire structure in one call, into one large object (or array). No matter how deeply nested the data is, you call json_decode() once and you're done. That's why Army is not a JSON string any more.

Boann
  • 48,794
  • 16
  • 117
  • 146
  • Hi Boan, sorry I had to start another question post for my JSON/PHP venture since it's prohibited to ask sub questions in your main questions in SO but I am having way too much confusion with the different answers and I just want to ask you this, you said json_decode() already decodes everything in the given JSON string. (1) how do I retrieve the value of a key who's inside another key. Like in a given sample below, how can I get the value of user325648's knights? 325648 is inside Knights{} who's inside Army{}. – user3613603 May 11 '14 at 17:24
  • (2) How can I store all contents of Army{} into a variable so I can save it in DB or echo it. (3) How can I get each keys inside Knights{} and echo them one by one. Basically the entire JSON file contains other info I would be needing but I just need to get owned_items and display its contents, also to save it in database later. owned_items and Sample JSON is `{"buildings":"townhall","Army":{ "Paladins":{ "325648":0, "546545":4 }, "Knights":{ "325648":-2, "546545":0 } } }` – user3613603 May 11 '14 at 17:28
  • @user3613603 (1) If you decode it as an object (this is what json_decode does if you set the second parameter `false` or simply leave it out entirely) then `echo $phpArray->Army->Knights->{325648};` If you decode it as an array, then `echo $phpArray['Army']['Knights'][325648];` – Boann May 11 '14 at 17:29
  • Here's what I'm trying to display on my website http://s23.postimg.org/wfogo8o57/Capture.png – user3613603 May 11 '14 at 17:35
  • @user3613603 (2) To get the army data into its own variable `$army = $phpArray->Army`. To display it, use `print_r` or `var_dump`, or for more control over its appearance, [`foreach`](http://www.php.net/manual/en/control-structures.foreach.php). To save that structure to a database, call json_‌**en**code to pack it back as a single string: `$army = json_encode($army);` and then save the string to the database as you would any other simple value. – Boann May 11 '14 at 17:35
  • @user3613603 (3) Loop the knights data using `foreach`. For example: `foreach ($phpArray->Army->Knights as $user => $knights) { echo "User ID: $user; Knights: $knights."; }` – Boann May 11 '14 at 17:37
  • I see, how about if I try to do `echo $phpArray['Army']['Knights']` or `echo $phpArray->Army->Knights` can I get it to show `325648:-2 546545:0`? Perhaps with added string manipulation? – user3613603 May 11 '14 at 17:38
  • Ah now that makes sense. In your opinion, should I have just used TRUE instead of FALSE? or is the difference between the two are only the -> and the [] ways of writing the code – user3613603 May 11 '14 at 17:42
  • `echo $phpArray['Army']['Knights']` and `echo $phpArray->Army->Knights` will always either display `Array` or just not work, because echo doesn't know what to do with the structure. To control how it is displayed, you must use `foreach`. – Boann May 11 '14 at 17:42
  • I like `false` (object) better because of the cleaner syntax (`->`) for using it. `false` is the default, so you can leave that parameter out entirely when calling json_decode. – Boann May 11 '14 at 17:45
  • Ok I will try that now. I just need to pull out owned_items from the decoded JSON file, owned_items contains the sample above. From this point we don't exactly know what data is inside owned_items, so I'm going to do a foreach, it should work just fine for keys having a value, my worry is for keys that contains array (or anything more than just a value). I could jsut be confusing myself. I'll read through your replies then test a couple – user3613603 May 11 '14 at 17:48
  • Thank you so much. I think I had it working now. As per your suggestion, I'm sticking with FALSE. I did json_decode() the JSON contents and did a `$army=$phpArray->Army;` then finally did a `echo json_encode($army);` and that displayed the contents of army in the page, no `=>` or any other gibberish, just that part of the code, just the way I want it. :) – user3613603 May 11 '14 at 18:27
  • By the way, what happens if I try to do a `$army = $phpArray->Army;` when the key "Army" is not in the JSON. Will that cause error or will just continue to next line of code? Coz I need it to ignore if "Army" is not in it – user3613603 May 11 '14 at 18:35
  • (1) `=>` isn't gibberish. It's part of the syntax of `foreach` that lets you tell it into which two named variables to put each key-value pair. (2) If Army isn't in your data, you will get an error when trying to read it ("Notice: Undefined property"). If you want to ignore data which doesn't have this key, wrap the relavant code in an if-[isset](http://www.php.net/manual/en/function.isset.php): `if (isset($phpArray->Army)) { /* do something */ }`. – Boann May 11 '14 at 19:10
  • Hi Boann, perhaps you can shed light on this other post. The people responding there seem more confused than I am, and the topic is going a different direction. You seem to know good things about these issues http://stackoverflow.com/questions/23602959/is-array-not-working-when-reading-json-in-php – user3613603 May 12 '14 at 08:07
  • @user3613603 It looks like you already got your answer: use `is_object`, not `is_array`. – Boann May 12 '14 at 08:40
  • lol. Thanks much, it's weird to use is_object to see if a value has arrays in it or not but it seem to be working so I'll make use of it. As usual, you're the best – user3613603 May 12 '14 at 08:44
  • After a couple of testings with is_object() and is_array(), I think I have a conclusion. I think it considers `{"1st Payment":"50","2nd Payment":"75"}` as object and `[{"1st Payment":"50","2nd Payment":"75"}]` as array. My JSON file contains a lot of data enclosed in `{` and `}` but some groups are enclosed in `[{` and `}]` and those are being detected as arrays. – user3613603 May 12 '14 at 09:45
  • @user3613603 That's correct. `[`...`]` is JavaScript notation for an array, `{`...`}` is JavaScript notation for an object, and `[{`...`}]` is an object inside a 1-element array. – Boann May 12 '14 at 09:50
  • Thank you, this made it all clear form e. I am getting stuck with that issue because of this detail that I failed to notice.:) – user3613603 May 12 '14 at 12:33
-1

It's because the output from your json_decode looks like this:

object(stdClass)(
  'buildings' => 'townhall',
  'Army' => object(stdClass)(
    'Paladins' => object(stdClass)(
      325648 => 0,
      546545 => 4
    ),
    'Knights' => object(stdClass)(
      325648 => -2,
      546545 => 0
    )
  )
)

Army is a standard object so it can't know how to echo it. You can however var_dump it:

var_dump($phpArray->Army);

The easiest solution is to treat it as a normal array with:

$phpArray = json_decode($jsonlogcontents, true);
Tom Holder
  • 311
  • 4
  • 5