Iterate through JSON String in PHP?

160
August 12, 2021, at 06:30 AM

it seems to be a really easy question, but I am a little bit struggling: I am receiving a JSON String via JavaScript. Now I would like to iterate through the element. The resulting string has this form: {"title":value,"title2":value}

How can I iterate through this JSON string without knowing the key and value? I would like to get this output:

title -> value

title2 -> value2

I tried it this way:

$json = file_get_contents('php://input');
$array = json_decode($json,true);
$response = "Test";
foreach($array as $key=>$val) {
    $response = $response. "$key : $val";
}
echo json_encode($response);

It only returns "Test". If I change it to echo json_encode($array), it returns the mentioned JSON String.

Answer 1

You mention javascript and php in your question, so I'm going to answer for both. Here is JS, two different ways. I believe that foreach is being deemphasized in favor of the (of) construct now, but I don't work primarily in JS:

var json = '{"title": 12, "title2": "text"}';
var data = JSON.parse(json);
Object.keys(data).forEach(function(key) {
  console.log(key + ' -> ' + data[key])
})
for(key of Object.keys(data)) {
  console.log(key + ' -> ' + data[key]);
}

And for PHP:

You can parse the json string into an array using json_decode:

$json = '{"title": 12, "title2": "text"}';
$arr = json_decode($json, true);
foreach($arr as $key=>$val) {
    echo "$key : $val";
}

true parses it into an array instead of a std object.

https://www.php.net/manual/en/function.json-decode.php

Answer 2

Because of response's format you must decode the decoded format in order to take the object as you want

$json = '{"title": 12, "title2": "text"}';
$encoded=json_encode($json);
$decoded=json_decode($encoded);
$ddecode=json_decode($decoded);
foreach($ddecode as $key=>$val) {
    echo "$key -> $val";
}

Output :

title -> 12 title2 -> text
Rent Charter Buses Company
READ ALSO
Clean code best practice in PHP. Less DB calls or friendlier code [closed]

Clean code best practice in PHP. Less DB calls or friendlier code [closed]

Want to improve this question? Update the question so it can be answered with facts and citations by editing this post

150
Upgrade python version in GCP Composer

Upgrade python version in GCP Composer

We have a GCP composer with Python version 3I would like to update the version to Python 3

151
How to combine a front-end library and Node tool in one package without front-end bloat?

How to combine a front-end library and Node tool in one package without front-end bloat?

I have two libraries which I'm considering combining into oneOne is a front-end library (although it can be used in Node), the other is a command-line tool, with some Node dependencies

149