How to get multiple array JSON Data - php

I have Json Data with multiple array, and i try to get the data inside effect_property, but it keep return nothing.
Here is my code
$json = file_get_contents('data.json');
$json_data = json_decode($json,true);
for($i = 0; $i < $count_data_action; $i++){
$path_data_action = $json_data[t03_action][data][$i][effect_property];
}
when i print the $path_data_action it show something like this:
{"duration":1,"delay":0,"propTo":{"source":"image","source_path":"../uploads/17041409353289557288/","source_file":"1704141604180616.jpg","source_name":"image1.jpg"},"beforeAction":"0","action_order":"1"}
How can i get the source_path?

Probably the JSON you are decoding with :
$json_data = json_decode($json,true);
contains another JSON string at key effect_property. You could change that to JSON Object and it should work fine.
Otherwise, you could use json_decode again, like :
for($i = 0; $i < $count_data_action; $i++){
$path_data_action = $json_data[t03_action][data][$i]effect_property];
$pathDataActionArr = json_decode($path_data_action , true);
$sourcePath = $pathDataActionArr['propTo']['sourcePath'];
}
Furthermore, to know any last occurred error with JSON encoding/decoding
json_last_error — Returns the last error occurred
UPDATE : I tried to decode the JSON you posted with code :
$fileContent = file_get_contents("/home/tarun/Desktop/test/abcd");
$jsonArray = json_decode($fileContent,true);
var_dump($jsonArray['t03_action']['data'][9]['effect_property']);
$effectPropertyArr = json_decode($jsonArray['t03_action']['data'][9]['effect_property'],true);
if(isset($effectPropertyArr['propTo']['source_path'])) {
var_dump($effectPropertyArr['propTo']['source_path']);
} else {
var_dump("No such key!");
}
Here, not all your elements of the array at key effect_property contains source_path. That's why :
if(isset($effectPropertyArr['propTo']['source_path'])) {
The above is working fine, with output :
/home/tarun/Desktop/test/temp.php:6:
string(205) "{"duration":1,"delay":0,"propTo":{"source":"image","source_path":"../uploads/18032022375907620062/","source_file":"1804100413270066.jpg","source_name":"Penguins.jpg"},"beforeAction":"0","action_order":"1"}"
/home/tarun/Desktop/test/temp.php:10:
string(32) "../uploads/18032022375907620062/"

// decoded array passed key of that array
$json_data['propTo']['source_path'];

try this ,Its working for me.
var data = {"duration":1,"delay":0,"propTo":{"source":"image","source_path":"../uploads/17041409353289557288/","source_file":"1704141604180616.jpg","source_name":"image1.jpg"},"beforeAction":"0","action_order":"1"}
alert(data.duration);
var Prop = data.propTo;
alert(Prop.source_path);`enter code here`

Related

PHP API wont return right data

So im using the spaceX api to try and understand retrieving data using php a bit more,
my base url is : https://api.spacexdata.com/v5/launches/
from here it returns:
from here i want the webcast link, but i cannot acces it somehow.
my current code:
$api_url = 'https://api.spacexdata.com/v5/launches/';
$json_data = file_get_contents($api_url);
$data = json_decode($json_data, true);
//var_dump($data);
$i = 0;
foreach ( $data as $launches)
{
$i++;
if($i > 2) break;
var_dump($launches["fairings"],
$launches["links"], '<br/>');
}
that returns:
how can i return the 'webcast' url
$launches["links"]["webcast"]
You can chain your properties to go down the objects/arrays values... This is the same as doing
$links = $launches["links"];
$links["webcast"];

how can produce json array with while in php

i want return my data from mysql to json array with do while loop.
when i return one record with json it is well. but i want return list of array in one json array.
how can do that with index in while? my code have error and i don't know how can do it. with one record it is well but more can't.
$json="array(";
do{
$json=."'$row_query['id']'=>array('fname'=>$row_query['fname'],'lname'=>$row_query['lname']),";
} while ($row_query = mysqli_fetch_assoc($query));
json=.")";
echo json_encode($json,JSON_UNESCAPED_UNICODE);
There's no need to add quotes, brackets, parentheses or whatever. json_encode function will do it for you. Just provide an array to it:
$json = [];
while ($row_query = mysqli_fetch_assoc($query)) {
$json[$row_query['id']] = [
'fname'=>$row_query['fname'],
'lname'=>$row_query['lname'],
];
}
echo json_encode($json,JSON_UNESCAPED_UNICODE);
This is the most super easy version. You may try this.
$json = new array();
do{
array_push($json,$row_query);
} while ($row_query = mysqli_fetch_assoc($query));
or
$json = [];
do{
$json[] = $row_query;
} while ($row_query = mysqli_fetch_assoc($query));
Atlast encode your json variable.
$json = json_encode($json);
echo $json;

PHP JSON multiple echo value

In addition to the question yesterday: Question
I got multiple (3) Items in the json file:
results.json
["{\"Produkt\":{\"Produktkategorie\":\"Artikel1\",\"Optionen\":{\"MaxBreite\":\"250\",\"MaxHoehe\":\"150\",\"MinBreite\":\"10\",\"MinHoehe\":\"5\",\"ProduktStaerke\":\"3\",\"KantenAuswahl\":\"Kante1\"}}}","{\"Produkt\":{\"Produktkategorie\":\"Artikel2\",\"Optionen\":{\"MaxBreite\":\"250\",\"MaxHoehe\":\"150\",\"MinBreite\":\"10\",\"MinHoehe\":\"5\",\"ProduktStaerke\":\"3\",\"KantenAuswahl\":\"Kante2\"}}}","{\"Produkt\":{\"Produktkategorie\":\"Artikel3\",\"Optionen\":{\"MaxBreite\":\"250\",\"MaxHoehe\":\"150\",\"MinBreite\":\"10\",\"MinHoehe\":\"5\",\"ProduktStaerke\":\"3\",\"KantenAuswahl\":\"Kante3\"}}}"]
I want echo all three value from "Produktkategorie" and the value "MaxBreite"
It should look like this:
Artikel1 - 250
Artikel2 - 250
Artikel3 - 250
My code looks like this:
$json = file_get_contents('results.json');
$json = json_decode($json, true);
$anzahl = count($json) -1;
$anzahlstart = 0;
while ($anzahlstart < $anzahl) {
$json = json_decode($json[$anzahlstart], true);
$ProduktkategorieFile = $json['Produkt']['Produktkategorie'];
$MaxBreiteFile = $json['Produkt']['Optionen']['MaxBreite'];
echo $ProduktkategorieFile. "-" .$MaxBreiteFile;
$anzahlstart ++;
}
Unfortunately my Code throws a error after passing first line:
Notice: Undefined offset: 1 in
After that I don't get any result.
Kings of coding, could you help me again please :)
Do you need like this?:-
<?php
$json_string = file_get_contents('results.json');
$json = json_decode($json_string, true);
// I hope the above line gives you exact json what you shown to us
foreach ($json as $jso){
$array = json_decode($jso, true);
echo $array['Produkt']['Produktkategorie'].' - '.$array['Produkt']['Optionen']['MaxBreite'];
echo PHP_EOL;
}
Output:-https://eval.in/728430
Note:- If yes then I hope you are able to get other values easily.Thanks
The problem is with the $json variable name: You're reassigning it on this line: $json = json_decode($json[$anzahlstart], true);
Rename this variable and you're good to go!
I would also replace the while loop with a foreach loop as shown in my example:
<?php
//With foreach
$original = '["{\"Produkt\":{\"Produktkategorie\":\"Artikel1\",\"Optionen\":{\"MaxBreite\":\"250\",\"MaxHoehe\":\"150\",\"MinBreite\":\"10\",\"MinHoehe\":\"5\",\"ProduktStaerke\":\"3\",\"KantenAuswahl\":\"Kante1\"}}}","{\"Produkt\":{\"Produktkategorie\":\"Artikel2\",\"Optionen\":{\"MaxBreite\":\"250\",\"MaxHoehe\":\"150\",\"MinBreite\":\"10\",\"MinHoehe\":\"5\",\"ProduktStaerke\":\"3\",\"KantenAuswahl\":\"Kante2\"}}}","{\"Produkt\":{\"Produktkategorie\":\"Artikel3\",\"Optionen\":{\"MaxBreite\":\"250\",\"MaxHoehe\":\"150\",\"MinBreite\":\"10\",\"MinHoehe\":\"5\",\"ProduktStaerke\":\"3\",\"KantenAuswahl\":\"Kante3\"}}}"]';
$decoded = json_decode($original);
foreach($decoded as $encodedProduct){
$product = json_decode($encodedProduct,true)['Produkt'];
echo $product['Produktkategorie'] . " - " . $product['Optionen']['MaxBreite'] . "\n";
}
//Original fixed code
$json = json_decode($original, true);
$anzahl = count($json);
$anzahlstart = 0;
while ($anzahlstart < $anzahl) {
$decodedJson = json_decode($json[$anzahlstart], true);
$ProduktkategorieFile = $decodedJson['Produkt']['Produktkategorie'];
$MaxBreiteFile = $decodedJson['Produkt']['Optionen']['MaxBreite'];
echo $ProduktkategorieFile. " - " .$MaxBreiteFile . "\n";
$anzahlstart ++;
}
Your problem is, that you are trying to decode an array of json string, instead of the string itself.
so that would be like this now.
$json = file_get_contents('results.json');
$json = json_decode($json[0], true); // notice [0];on this line.
...
After reading the other question, I have had this problem before, but you essentially need to do two things. in your ajax.
$.ajax({
...
data : JSON.stringify(data)
})
This changes an object into a json string,
Then on your server you do the decode.
something like this
$json = json_decode($jsonstringGoesHERE , true);
For more information in understanding the issue, have a look at this other post.
jQuery ajax, how to send JSON instead of QueryString

android, php, parsing JSON in php file sent from android

i have this JSON
{
"count":"3",
"num":"1",
"array":[
{
"id":"a_a",
"amount":56,
"duration":"0:12",
"time":1234566,
"type":0
},
{
"id":"a_a",
"amount":56,
"duration":"0:12",
"time":1234566,
"type":1
}
]
}
created it in android and send it by **HttpPost**
, i've tried a lot of ways to get the data in the php, my php file is this:
<?php
$response = array();
//$json_data = json_encode(stripslashes($_POST['jsonarray']))
$josn = file_get_contents("php://input");
$json_data = json_decode($josn,true);
$count = $json_data->{'count'};
$num = $json_data["num"];
$response["data"]=$count;
$response["data2"]=$num;
// echoing JSON response
echo json_encode($response);
?>
but $count and $num always returns null, any help please, and thanks.
$json_data = json_decode($josn,true);
this returns an array, not an object (which you are using later in the code). Use this to convert the json string to an object:
$json_data = json_decode($josn);
Or you could just use arrays, in which case your code should look like:
<?php
$response = array();
//$json_data = json_encode(stripslashes($_POST['jsonarray']))
$josn = file_get_contents("php://input");
$json_data = json_decode($josn, true); // using true to get array
$count = $json_data["count"]; // accessing array values as normal
$num = $json_data["num"]; // accessing array values as normal
$response["data"] = $count; // instead of setting $count first you could just add
$response["data2"] = $num; // the json_data array values directly to the response array
// echoing JSON response
echo json_encode($response);

Send and Decode Object Array via JSON

I have an array of People objects. I'm sending them to PHP but the way to get my objects back in PHP so I can manipulate them seems convoluted. Here's what I have, but it doesn't seem to return anything back to my AJAX Call. Right now I just have 1 Person Object in my array but I want to make sure everything is fine before I advance. In short, when I decode my JSON shouldn't it convert it to an Object in PHP? In the end I want an array of PHP objects that are People
Jquery
var people = new Array();
var person = new Person("Michael", "Jackson", 50);
localStorage.setItem(person.firstName + " " + person.lastName, JSON.stringify(person));
function Person(firstName, lastName, age)
{
this.firstName=firstName;
this.lastName=lastName;
this.age=age;
}
function getStorage(){
var tempPerson;
for(var i = 0; i < localStorage.length; i++)
{
tempPerson = $.parseJSON(localStorage.getItem(localStorage.key(i)));
people.push(tempPerson);
}
}
function getPeople(){
$.post(
"people.php",
{people : people},
function(data)
{
alert(data);
}
);
}
getStorage();
getPeople();
PHP
<?php
$personObj = Array();
$people = $_POST['people'];
for($i = 0; $i < count($people); $i++)
{
foreach($people[$i] as $person)
{
$streamObj = json_decode($person);
}
}
echo $personObj->$firstName;
In addition to making the change suggested by #Even Hahn, you need to change the data you are posting as follows:
$.post(
"people.php",
{people : JSON.stringify(people)},
function(data)
{
alert(data);
}
);
This way a single name/value pair is posted. The name is "people" and the value is a JSON encoded string of the array of Person objects.
Then when you call the following in the PHP code, you are decoding that JSON encoded string into an array on the PHP side.
$people = json_decode($_POST['people']);
I also see where you assign $personObj to an array, but I don't see where you put anything in the array.
Try moving your JSON decoding in your PHP:
$personObj = Array();
$people = json_decode($_POST['people']);
for($i = 0; $i < count($people); $i++)
{
foreach($people[$i] as $person)
{
$streamObj = $person;
}
}
echo $personObj->$firstName;
This is because $_POST['people'] is a JSON string which needs to be decoded.
Perhaps the PHP codes should be look like this:
<?php
$personObj = Array();
$people = $_POST["people"];
foreach($people as $p)
{
$val = str_replace("\\","",$p);
$personObj = json_decode($val);
}
echo $personObj->firstName;
?>

Categories