I know my JSON is valid, I'm wanting to pull all the KEY's out of the array and put them in an object. However it seems I can either access ONE objects Key or Value, the entire array, or one key value pair. I have not figured out how to parse out all the keys, or all the values in the array.
Here is what I've tried:
print_r($json_obj) yields:
Array ( [0] => Array ( [0] => uploads/featured/doublewm-4097.jpg [1] => featured ) [1] => Array ( [0] => uploads/featured/moon-5469.jpg [1] => featured ) )
print_r($json_obj[0][1]) yields:
featured
print_r($json_obj[1][0]) yields:
uploads/featured/moon-5469.jpg
print_r($json_obj[1][1]) yeilds:
featured
print_r($json_obj[0][0]) yields:
uploads/featured/doublewm-4097.jpg
PHP Code:
<?php
$resultSet = '[["uploads/featured/doublewm-4097.jpg","featured"],
["uploads/featured/moon-5469.jpg","featured"]]';
$json_obj = json_decode($resultSet);
// print_r($json_obj);
print_r($json_obj[0][1]);
?>
The JSON validates per JSONLint
[
[
"uploads/featured/doublewm-4097.jpg",
"featured"
],
[
"uploads/featured/moon-5469.jpg",
"featured"
]
]
I would like to end up with a object with all the keys in the json_obj... ie:
json_obj = array(
'uploads/featured/moon-5469.jpg',
'uploads/featured/doublewm-4097.jpg'
);
If your input is always in the same format, you can handle it like this
$tmp = json_decode($resultSet);
$json_obj = array();
foreach ($tmp as $values) {
array_push($json_obj, $values[0]);
}
This will give you $json_obj in the desired format with a hardcoded $resultSet like the one you provided.
maybe this is what you are looking for:
json encode server-side like:
echo json_encode($html);
json parse clientside like
var str = JSON.parse(data);
alert (JSON.stringify(str))
I managed to fix it like this:
Changing the json object to this format
data = { gallery: gallery_name,
files: [
// imagefile,imagefile,imagefile...
]
};
And the using the following php
$resultSet = json_decode($_GET['submittedResults'], true);
$gallery = $resultSet['gallery'];
$files_to_zip = $resultSet['files'];
Related
I am consuming a web service that returns some XML data. The problems start when I convert the xml data to json. Some elements that are supposed to return an array of objects, when they have only one value, they are not converted to an array with a single object inside, they turn into an object. So instead of having:
{
"products":[ { "title":"Title 1", "attributes":[{"color":"blue"}] } ]
}
I get
{
"products":{ "title":"Title 1", "attributes":{"color":"blue"} }
}
and the php array looks like this
[products] => Array ( [title] => Title 1 [attributes] => Array ( [color] => blue ) )
instead of this
[products] => Array ( [0] => Array ( [title] => Title 1
[attributes] => Array ([0] => Array ([color] => blue ) ) )
So what I have done is the below:
$xml = simplexml_load_string($messageData);
$json = json_encode($xml);
$array = json_decode($json, TRUE);
if (isset($array['products']) && !isset($array['products'][0])) {
$array['products'] = array($array['products']);
}
I check if there is an array named products and if it doesn't have an index 0, I nest it inside a new array.
This does the job. Then I do the same for the attributes array like this:
$products = $array['products'];
$array['products'] = [];
foreach ($products as $product) {
if (isset($product['attributes']) && !isset($product['attributes'][0])) {
$product['attributes'] = array($product['attributes']);
}
array_push($array['products'], product);
}
Here, I bind the products array to a variable called products to use it in the loop, then I empty the array and after I create the new attributes array, I populate the products array with the changed products.
My question is:
Is there a better way to deal with this thing? I don't like what I am doing here, but I can't think of anything else...
EDIT
This is my soap request:
$client = new SoapClient($wsdl, $soapOptions);
$soapHeader = WsSecurity::createWsSecuritySoapHeader($username, $password, false, $synced, 60, true, true, false, true);
$client->__setSoapHeaders($soapHeader);
$response = $client->dateRetrieveMovement($dateMovementRequest);
$movements = $response->DateMovementRequestResult->movements;
$movementInfo = $movements->movementInfo;
$messages = $movementInfo->messages->messageExchanged;
$messageData = $messages->IEMessage->xmlData;
$xml = simplexml_load_string($messageData);
$json = json_encode($xml);
$array = json_decode($json, TRUE);
The question is "is there a better way of doing the XML to JSON conversion", and I think the answer is "not without doing some coding".
Standard XML-to-JSON conversion libraries simply don't know enough about the semantics of your data model to produce a decent representation of your data. In theory a tool could try an extract such information from a schema, or elsewhere, but I don't know of any that does.
Writing a custom XSLT transformation to produce exactly the JSON you want is not too difficult, especially with XSLT 3.0, and this may well be less effort than patching up the JSON in the receiving application in the way you describe.
I'm trying to decode json array to php array using json_decode, but it's displaying a blank page
Here's the json array
[["id":"2","name":"Sam Nju","photo":"1510074080885.jpg","qty":"10","price":"10000.00"],["id":"3","name":"Daniel","photo":"1510074047056.jpg","qty":"0","price":"40000.00"]]
Here's the code to decode json
$json = file_get_contents('http://localhost/example/index.php/destinations/json');
$data = json_decode($json,true);
$names = $data['result'];
echo "<pre>";
echo $names;
print_r($names);
Thanks
For obtaining proper JSON using json_decode() and json_encode() follow these guidelines:
json_decode() :
This function only works with UTF-8 encoded strings.
Returns the value encoded in json in appropriate PHP type. Values true, false and null are returned as TRUE, FALSE and NULL respectively. NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.
The key and value must be enclosed in double quotes single quotes are not valid.
Your JSON:
[["id":"2","name":"Sam Nju","photo":"1510074080885.jpg","qty":"10","price":"10000.00"],["id":"3","name":"Daniel","photo":"1510074047056.jpg","qty":"0","price":"40000.00"]]
apears to be invalid. Arrays use [] while objects use {}.
This is an example of how a proper PHP array structure would look like prior to doing json_encode() (before sending):
// array structure in PHP to get proper JSON
Array ( [0] => Array ( [id] => 2 [name] => Sam Nju [photo] => 1510074080885.jpg [qty] => 10 [price] => 10000.00 ) [1] => Array ( [id] => 3 [name] => Daniel [photo] => 1510074047056.jpg [qty] => 0 [price] => 40000.00 ) )
which was obtained using the following:
json_decode('[{"id":"2","name":"Sam Nju","photo":"1510074080885.jpg","qty":"10","price":"10000.00"},{"id":"3","name":"Daniel","photo":"1510074047056.jpg","qty":"0","price":"40000.00"}]', true)
which would mean doing this:
$myArray = array();
$firstPerson = array();
$secondPerson = array();
$firstPerson['id'] = 2;
$firstPerson['name'] = "Sam Nju";
// ...
$secondPerson['id'] = 3;
$firstPerson['name'] = "Daniel";
// ...
array_push($myArray, $firstPerson);
array_push($myArray, $secondPerson);
// or $myArray[0] = $firstPerson; and $myArray[1] = $secondPerson;
While valid JSON would look like this:
{{"id":"2","name":"Sam Nju","photo":"1510074080885.jpg","qty":"10","price":"10000.00"},{"id":"3","name":"Daniel","photo":"1510074047056.jpg","qty":"0","price":"40000.00"}}
If you are getting the data from a database you might want to use something like this:
$result = mysqli_query($con, "SELECT .... // database query, $con is connection variable
$myArray = array();
while($row = mysqli_fetch_array($result))
{
$tempArray = array();
$tempArray['id'] = $row[0];
$tempArray['name'] = $row[1];
$tempArray['photo'] = $row[2];
// ...
array_push($myArray, $tempArray);
}
// use print_r($myArray); to test it out.
Although your code looks correct, your JSON data is invalid. Objects are enclosed by {}, not []. Replace the JSON with this, and it should work.
[
{
"id": "2",
"name": "Sam Nju",
"photo": "1510074080885.jpg",
"qty": "10",
"price": "10000.00"
},
{
"id": "3",
"name": "Daniel",
"photo": "1510074047056.jpg",
"qty": "0",
"price": "40000.00"
}
]
Also above answer already mentioned it:
Your JSON is invalid. You can check this e.g. with an JSON linter like https://jsonlint.com/
Plus, you're referencing names with $names = $data['result'];. However, in your provided JSON there is no array (or better object), with key "result".
You may look up your PHP's error log file to understand where the problem lies.
I have an imaging web service where I want to send as a JSon the results of a query in PHP to my application.
Basically, my result contains multiple results with each one having the same and following attributes
id
date
owner
extension
filename
I want to put them inside an array in such a way that each item's result is an array itself inside the bigger array just like the below image.
How can I accomplish this?
Do you need this?
$arrayInArray = array(
array("Thing1","Thing2"),
array("Thing3","Thing4")
);
After your query you can build an array the way you want (these are called multidimensional arrays) by using
$res = mysqli_query("SELECT `xx` FROM `xx`");
$images = array();
while($row = mysqli_fetch_array($res)) {
$images[] = $row;
}
return json_encode($images);
Say you have an image $image which is an array containing your attributes id, filename and so on.
Then just create array that hold all images and push it into that.
$images = [];
$images[] = $image; // Push image into images
// Or if you don't already have $image, you can also create and push at the same time
$images[] = [
'id' => 1,
...
];
You can generate array like this
<?php
$data=[
0=>[
'id'=>1,
'date'=>'3/3/2017',
'owner'=>'ownerName',
'extension'=>'yourExtension',
'filename'=>'YourFileName'
],
1=>[
'id'=>2,
'date'=>'3/3/2017',
'owner'=>'ownerName',
'extension'=>'yourExtension',
'filename'=>'YourFileName'
]
];
$jsonData=json_encode($data)//convert into jsondata to send
?>
Then send this data.
This is called multidimensional array , simple syntax for your requirement is
Array(
[0] => Array
(
[id] => 1,
[date] => 2021,
[owner] => 'shebin',
[extension] => 'png',
[filename] => 'new'
)
)
In order to get the above structure you can simply use :
In this example ,
consider $images as multidimensional array so code will be like
$images[0]['id'] = 1 ;
$images[0]['date'] = 2021 ;
$images[0]['owner'] = 'shebin' ;
$images[0]['extension'] = 'png' ;
$images[0]['filename'] = 'new' ;
Instead of 0 you can use variable so you can create multiple set of this array
$images[$i]['id'] = 1 ;
I have dataset like the following, one of my table column let say prices column store prices in json format, example given below.
<?php
$dataSet[] = array(
"product_id" => 1,
"prices" => '{"1":"29990", "2": "10000"}'
);
foreach ($dataSet as $dataRow)
{
$pricesStdClassObject = json_decode($dataRow['prices']);
// Convert stdClass Object into array
$pricesArray = (array) $pricesStdClassObject;
print_r($pricesArray);
}
?>
The output of print_r($pricesArray) is the following
Array ( [1] => 29990 [2] => 10000 )
Then why print_r($pricesArray[1]) give me error
A PHP Error was encountered
Severity: Notice
Message: Undefined offset: 1
But why?
And finally i found the solution:
According to the documentation here and from the forum here I found a ‘assoc’ parameter of json_decoded method that used with this method and by default its value is FLASE, json_decoded return stdClass objects if you want the returned objects converted into associative arrays then you have to make the ‘assoc’ parameter value to TRUE like the following.
$pricesStdClassObject = json_decode($dataRow['prices'], TRUE);
So the above example code will become like this
<?php
$dataSet[] = array(
"prices" => '{"1":"29990", "2": "10000"}'
);
foreach ($dataSet as $dataRow)
{
$pricesArray = json_decode($dataRow['prices'], TRUE);
// returned objects will be converted into associative arrays.
print_r($pricesArray);
}
?>
And then you can access the indexed value with no error message :)
print_r($pricesArray[1]); output: 29990
Array type casting with json decoded StdClass Objects is not working properly, you can skip the following piece of code if you are using the ‘assoc’ parameter.
// Convert stdClass Object into array
$pricesArray = (array) $pricesStdClassObject;
I'm trying to make my json output in the following format below, but I do not know how to code it to make it display in just format... I just have the values, any kind of help I can get on this is greatly appreciated!
{
"firstcolumn":"56036",
"loc":"Deli",
"lastA":"Activity",
"mTime":"2011-02-01 11:59:26.243",
"nTime":"2011-02-01 10:57:02.0",
"Time":"2011-02-01 10:57:02.0",
"Age":"9867 Hour(s)",
"ction":" ",
"nTime":null
},
{
"firstcolumn":"56036",
"loc":"Deli",
"lastA":"Activity",
"mTime":"2011-02-01 11:59:26.243",
"nTime":"2011-02-01 10:57:02.0",
"Time":"2011-02-01 10:57:02.0",
"Age":"9867 Hour(s)",
"ction":" ",
"nTime":null
}
You can use a PHP associative array to set the key => value's of your array to be converted to json. As you would expect the key of the php associative array becomes the key of the JSON object, and the same with the values.
$array = array(
'firstcolumn' => '56036',
"loc" => "Deli",
"lastA" => "Activity",
"mTime" => "2011-02-01 11:59:26.243",
"nTime" => "2011-02-01 10:57:02.0",
"Time" => "2011-02-01 10:57:02.0",
"Age" => "9867 Hour(s)",
"ction" => "",
"nTime" => NULL
);
You can do both arrays like this (using previous array to show concept but can replace with that same array())
$array2 = $array1;
$array2['firstcolumn'] = "56037";
$botharrays = array($array, $array2);
What we just did is put both sub arrays into one containing array so that when you encode the json it has each object separately.
array( array1, array2 )
Then use json_encode() to encode the array into the json format you requested
$JSON= json_encode($array);
or
$json = json_encode($botharrays);
I think you are looking for this:
$json = json_encode($myArray);
print_r($json);