Cannot loop through items in JSON (php) [duplicate] - php

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 4 years ago.
i have the following Json sent via ajax to test.php:
[{},{"product[]":"john","qty[]":"12","price[]":"100","total[]":"1200"},{"product[]":"juan","qty[]":"22","price[]":"3.5","total[]":"77"},{"product[]":"louis","qty[]":"99","price[]":"1.22","total[]":"120.78"},{"product[]":"paul","qty[]":"5","price[]":"2.1","total[]":"10.5"},{"product[]":"carl","qty[]":"9","price[]":"14","total[]":"126"},{"total_amount":"1533.00"}]
In my php file I am trying to loop through each individual product[], qty[], price[] and list values:
<?php
$obj = json_decode($_POST["mydata"]);
header('Content-Type: application/json');
// echo json_encode($obj[1]->{'product[]'}); //(works)
foreach($obj as $item) {
echo $item['product[]'].'<br>';
echo $item['price[]'].'<br>';
echo $item['qty[]'].'<br>';
echo $item['total[]'].'<br>';
}
?>
but this throws an error.
What is wrong in my loop?

There are a couple of things wrong with the code, the first is that you decode as objects and try and use this as an array. You need to pass true as the second parameter to json_decode() to make it an associative array.
The second is that your array contains elements which don't have all of the details. The last element only has "total_amount", so none of the other fields exist. This is why I use
if ( isset($item['product[]'])){
to check the object before outputting the data...
$obj = json_decode($_POST["mydata"], true);
header('Content-Type: application/json');
foreach($obj as $item) {
if ( isset($item['product[]'])){
echo $item['product[]'].'<br>';
echo $item['price[]'].'<br>';
echo $item['qty[]'].'<br>';
echo $item['total[]'].'<br>';
}
}

Pass true as second argument to json_decode.
Per the documentation:
assoc
When TRUE, returned objects will be converted into associative arrays.
So your code becomes:
$obj = json_decode($_POST["mydata"], true);
Also note that the first entry in your array is empty, so you're gonna have to check for that.

Related

How to dynamically insert JSON data into a PHP array for foreach [duplicate]

This question already has answers here:
How to create a JSON object
(5 answers)
Closed 3 years ago.
I have the following PHP code, which gets executed when I hit the Submit button in a form:
// Save data
if(isset($_POST['save'])){
$newDataArr = array();
foreach ($data_array[0] as $k=>$v){
$newDataArr[] = array($k => $_POST[$k]);
}// ./ foreach
echo json_encode($newDataArr);
}
The echo I get is the following:
[{"ID->id":"esKZSCDfIC"},{"DT->createdAt":"2020-01-26T13:02:42"},{"DT->updatedAt":"2020-01-26T13:02:42"},{"ST->aString":"hey1"},{"NU->number":123},{"GPS->coords":["2.2222","44.4444"]},{"BL->aBool":false},{"AR->theArray":["xx","ww"]},{"FL->theFile":"https:\/\/xscoder.com\/xserver\/uploads\/6dydDtoTt5JjZzFc5L5V_image.jpg"},{"PO->userPointer":"vbN3b0C7bC"}]
Then I'll have to add that array into my JSON file as it follows:
$data = json_encode(array_values($newDataArr), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
file_put_contents('Test.json', $data);
But of course the syntax of my $newDataArr is not the right one, each JSON object must not be inside the { }, so this:
{"ID->id":"esKZSCDfIC"},
must become:
"ID->id":"esKZSCDfIC",
Is there a way to dynamically create a valid JSON array and push it to my Test.json file?
I've been through many posts on StackOverflow, but the result I get is always the same. I must use the PHP code above to get keys and values from my HTML inputs.
Instead of creating and pushing a new array on each iteration, set the values this way:
$newDataArr[$k] = $_POST[$k];
Hope this helps.

How can i Iterate through data returned in Ajax success? [duplicate]

This question already has answers here:
How to loop through PHP object with dynamic keys [duplicate]
(16 answers)
Closed 5 years ago.
How can I iterate to get id value? This is my array:
[{"email_id":"gayatri.dsf#detedu.org","Id":"216"}]
tried
<?php
foreach($faculty as $value)
{
echo $value['Id'];
}
?>
Gives an error
Use of undefined constant Id - assumed Id
This is a json which is basically a string, to be more precise the given json contains a list (currently 1 element):
[{"email_id":"gayatri.dsf#detedu.org","Id":"216"}]
You need to convert it to an array first:
$jsonValues = json_decode($json, true); //here you will have an array of users (1 now)
foreach($jsonValues as $faculty) //for each user do something
{
echo $faculty['Id'];
}
This is JSON format. First you have to decode it. Example:
$a = '[{"email_id":"gayatri.dsf#detedu.org","Id":"216"}]';
$dec = json_decode($a);
echo $dec[0]->Id;
Result: 216
Decoded you have an array, containing exactly one object. You have to access the object properties with -> then.
With JSON [] brackets means an array, while {} brackets mean objects. Learn more: https://en.wikipedia.org/wiki/JSON

How to access object data inside an array and object after json_encode executed? [duplicate]

This question already has answers here:
Get value from JSON array in PHP
(4 answers)
Closed 6 years ago.
I have a json data from API and i want to insert them to my database table. I have extract $data using json_encode function, but when i tried to access data inside $myJson with some of this code, it gives me an error result.
$data = '{"posts":[{"post":{"math_score":"85","history_score":"70"}}]}';
$myJson = json_decode($data);
foreach ($myJson as $mj){
echo $mj['math_score'];
// echo $mj->math_score; <= error
// echo $mj[0]->post->math_score; <= error
// echo $mj->post->math_score; <= error
}
The error : Invalid argument supplied for foreach().
sorry for my bad grammar, any answer will be greatly appreciated. Thanks
There is built in php function json_decode()
Try
$json = '{"posts":[{"post":{"math_score":"85","history_score":"70"}}]}';
$json = json_decode($json);
echo $json->posts{0}->post->math_score;
By default json_decode return object. If you want an array then you need to pass second argument true to json_decode.
Try it with Array
$json = '{"posts":[{"post":{"math_score":"85","history_score":"70"}}]}';
$json = json_decode($json, true);
foreach ($json['posts'] as $mj)
{
echo $mj['post']['math_score'];
}

Parsing JSON from a URL (PHP CURL) [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 6 years ago.
So I've been stumped and I'm not sure how I would continue this
as an example let's just use books.com as the URL and let's say the JSON response from the URL is
[{"title":"first_title","description":"second_title"},
{"title":"second_title","description":"second_description"}]
How would I print all of the titles (just the titles) without knowing exactly how many there are.
I know that I would need to loop through the JSON but I'm unsure how, if I could have any guidance that would be fantastic.
You should get more familiar with json_decode() and foreach().
First you need to decode json (into array in this example) and then iterate through all elements.
Example of working code:
<?php
$json = '[{"title":"first_title","description":"second_title"},
{"title":"second_title","description":"second_description"}]';
$jsonArray = json_decode($json,true);
foreach($jsonArray as $entry) {
echo $entry['title'].'<br>';
}
Output:
first_title
second_title
This key is to actually convert the JSON response into a PHP associative array by using json_decode and then loop through it.
// Convert the JSON into a PHP associative Array
$response = json_decode($curlResponse,true);
// Loop through the array
foreach ($response as $value) {
echo $value['title'];
echo '<br/>';
}

unable to read json objects in php

I want to read JSON in php:
$productsArr = json_decode(stripslashes($_GET['object'])); //this give me word Array
stripslashes($_GET['object']) //gives me [{"code":"44-3"}]
echo $productsArr->{'code'}; //gives me nothing
I even tried this:
foreach($productsArr as $article)
{
echo $article->code; //nothing is echoing
}
How to access the JSON formatted data in a loop?
1) Force an array to be returned by supplied true to second argument of json_decode.
2) Ensure that this produces an array:
$productsArr = json_decode(stripslashes($_GET['object']), true);
print_r($productsArr);
Assuming it does. Access your elements as such:
echo $productsArr['foo']['bar'];

Categories