Encoding/Decoding JSON PHP

Can someone please help out here? I have this string in my PHP file and I can not figure out how to parse this. I have tried a million iterations of json_decode and json_encode and stripslashes. I am just trying to access the data for each key value.


This is sent to my PHP file so I can’t just type out $myData = ‘[{"key":"value"},{"key":"value"}]’ like many of the string examples I have found online.

I know this is the syntax because I can save it straight to the database as a whole but I can’t figure out how to extract the keys and values individually. I can do this with Javascript, so needing to be schooled in PHP on how to do this. Please help.

Just replace the backslash double quotes by double quotes and decode it.

$data = json_decode(str_replace(‘\"’, ‘"’, $source));

If I run:-

$string = '[{\"car\":\"mazda\",\"color\":\"red\"},{\"car\":\"lincoln\",\"color\":\"black\"}]' ;
$strip = stripcslashes($string);

var_dump($strip) ;
$dec = json_decode($strip);
var_dump($dec) ; 


I get:-

/test.php:12:string '[{"car":"mazda","color":"red"},{"car":"lincoln","color":"black"}]' (length=65)

array (size=2)
  0 => 
      public 'car' => string 'mazda' (length=5)
      public 'color' => string 'red' (length=3)
  1 => 
      public 'car' => string 'lincoln' (length=7)
      public 'color' => string 'black' (length=5)

Thanks for your reply. What’s interesting is that when I keep the string as a string I can save it to the database. But when I $data = json_decode(str_replace(‘"’, ‘"’, $source)); and try to save the $data variable to the database it comes back as empty.

What is happening here?

After using str replace and json decode, how do I then access the data?

Thanks for your reply.

How are you getting this printed information? With javascript I can use console.log($variable);

I tried running this and again when I try to save $dec to the database it returns empty, also tried encoding after decoding and returns empty in the databae.

I find it interesting that I can save the data as a string to the db but when I simply pass the data as is in a string with the backslashes and all as an argument to another function I can’t save it to the db in the second function. (It’s the same data, same format, same everything?)

I tried decoding in the original function before sending the data as an argument to the second function and it returns empty in the database there as well. So running stripslashes json decode whether in the first or second function returns the string as empty when saving to the db.

Could you elaborate as to how you can see printing out messages like the one in your post? Why it returns empty in the db after decoding it, and lastly, how would I access the data after decoding it?

That is the result of the var_dump()s in the PHP script. The dumps are included for diagnostic purposes only, so you can see the content of the variables, their type, size and content.
It shows that $strip, the result of stripcslashes($string) is a string of 65 characters and does indeed have the slashes stripped out.
And $dec, the result of json_decode($strip) is an array of two objects.

The data type you pass to the database must match the type that database column will accept. As shown the result of decoding is an array. The database won’t accept an array.

The databae will accept a string data type.

It’s an array, so however you need to access the data in the array. That could be by calling on an individual key, or iterating through all values in a foreach, it really depends upon your use case. But I’m not party to your intentions.

Yes, but where can I see the printed out information? With Js console.log I open dev tools and click console. Where do I find this when using var_dump()?

The column in the second function accepts tinytext whereas the first functions db column accepts text.
Thank you.

So right now, I am able to get the data by using $varA = $data[0]->car; This gives me mazda. I’m assuming $data references the entire array, the [0] references the first object, and the car references the first objects key. Is this correct? Could you give me an example of a for each loop in PHP for this? I’m not trying to get you to do this for me, just wanting to understand completely. In JS [] represents an object and {} represents an array, it seems to be the opposite in PHP. So just would like some clarification about using the correct syntax for extracting data from a PHP object inside a PHP array.

Thank you very much for taking the time! Really appreciate it.

var_dump outputs to standard out (AKA: The webpage.)

var_dump() will print the info out into the browser. It’s not to be used in production, but it can be handy in development/debugging to see exactly what the value of something is.
I used it in this example just to show you what the values of $strip and $dec are, so you know the data type, size, structure and content.

Yes. Though strictly speaking because it’s an object “car” is a property of the object, not a key.
By default json_decode gives you objects, setting the associative argument to true will give you arrays in place of objects which may be simpler for you.

$dec = json_decode($strip, true);

Results in a nested array like so:-

array (size=2)
  0 => 
    array (size=2)
      'car' => string 'mazda' (length=5)
      'color' => string 'red' (length=3)
  1 => 
    array (size=2)
      'car' => string 'lincoln' (length=7)
      'color' => string 'black' (length=5)

So you could access the colour of the second car with:-

$c2col = $dec[1]['color'];

This is a nested foreach:-

foreach($dec as $key => $car){
    echo "<li><a href='/car?carid=$key'><h2>More Info</h2></a>\n<dl>";
    foreach($car as $prop => $value){
        echo "<dt>$prop:</dt><dd>$value</dd>\n";
    echo "</dl>\n";

Though what you do in the array is up to you, this outputs a list of cars.

1 Like

Last question, in this snippet, you write ($dec as $key => $car) and then inside the foreach you use the key variable instead of the $car variable. Logically, it would seem that the $car variable would hold the value which in this case would be mazda and lincoln. So the $car variable is used to grab the car property but then stores the value inside the $key variable? Seems odd.

Here you write foreach($car as $prop => $value){ but then use both the $prop and $value variables. Is the $prop variable a built-in PHP variable or are you just using that? Is the $value variable a built-in PHP variable or are you just using that? Is the $car variable in the second for each loop simply holding the entire array?

I know this is a ridiculous question, it just helps me to magnify the details so that I can know that I know. I pretty much understand everything. I know you can print and echo out data with PHP but I didn’t know it would include the data type, size, and structure. Thank you!

I’ll start with the anatomy of a foreach construct.

foreach($array as $arrayKey => $arrayValue){ ... Do something ... }

The first variable $array is the array which is already defined, that you want to iterate through.
We then say as to tell it what to iterate as.
$arrayKey is optional, depending weather you need to access the array keys in the loop or not. Since it’s not a variable already defined, you can call it whatever you like: $k, $key, $id, whatever.
The arror => tell us we are looping both keys and values.
Finally the $arrayValue is the actaul value of each part of the array. Again call it what you will.
The two variables $arrayKey and $arrayValue are now accessible withing the loop.
If you don’t need the key, you could just have:-

foreach($array as $arrayValue){ ... Do something ... }

So in the outer loop I’m calling the key $key and the value (which is a nested array) $car, because it describes a car.
In the inner loop I access the nested arrays. I call the key $prop (my shorthand for property) as I don’t want to use $key again and cause confusion. And I call the value $value. But I choose those varable names, they are not built in, they are whatever you want them to be. But choose something that makes sense.

In the outer loop I access the key to add a query string to a URL. In a hypothetical scenario, I may have pulled data from a database in such a way that the array key matches the database ID of the item. This was done just as an example how and why you may access the key in foreach.
So each item in the array get’s a link to its own page.

Then in the inner loop, I list out the car’s properties, in this cae the make and colour or the car.
Again I use the key/value pair, this time to name the prperty on-screen.

To reiterate, the var_dump() would not typically be used in the final product, but it’s something you can add as a temporary line to see what’s going on. For example, it shows above that $dec is an array, which then explains why the database won’t accept it. So it can help solve some mysteries when debugging.

1 Like

Thank you very much!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.