PHP json_Encode an array of json_encode-ed arrays - php

Im not sure what is happening, but if i do
json_encode()
On a single array, i get valid json, but if i do something like
$ar['key'] = "name";
$array[] = json_encode($ar);
$json = json_encode($array);
It will return invalid json like so:
["{"key":"name"}"]
The expected outcome is
[{"key":"name"}]
I have searched for hours trying to find what is going on.

Due to lack of desired outcome, I can only assume you are trying to get a multidimensional array.
The correct way to achieve this would be to build an array of arrays, and then json_encode the parent array.
$data = array();
$data['fruits'] = array('apple','banana','cherry');
$data['animals'] = array('dog', 'elephant');
$json = json_encode($data);
Following this code, $json will have the following value
{"fruits":["apple","banana","cherry"],"animals":["dog","elephant"]}
It could then be parsed properly by javascript using jQuery.parseJSON()

Just json_encode the entire array.
$ar['key'] = "name";
$json = json_encode($ar);
json_encode returns a string, and json encoding a string will return a string.
Also it's json_encode, not $json_encode

Related

JSON - Normalize de format inside

I have converted an array in JSON. But the conversion puts arrays inside the JSON object.
My conversion is this:
{"title":"acastro","description":"teste acastro 4","category_id":29,"region_id":3,"city_id":3158063,"district_id":"1","contact":{"person":"Classe Car"},"0":{"make":"Mercedes-Benz"},"1":{"model":"GLC 220"},"2":{"engine_code":"Classe A"}
Have you can beginning in key "0":{"make":"Mercedes-Benz"}, the interior of the JSON changes anI i can not submit it to an api.
I need my JSON object to be entirely like its beggining:
"title":"acastro","description":"teste acastro 4","category_id":29,"make":"Mercedes-Benz","model":"GLC220",...
and so on.
I tried with json_encode and JSON_FORCE_OBJECT but without luck.
Any solutions?
You can try below code but its not tested:
$json = '{"title":"acastro","description":"teste acastro 4","category_id":29,"region_id":3,"city_id":3158063,"district_id":"1","contact":{"person":"Classe Car"},"0":{"make":"Mercedes-Benz"},"1":{"model":"GLC 220"},"2":{"engine_code":"Classe A"}}';
$newArr = array();
function recursiveArrayShiftToRoot($array, &$newArr=array()){
global $newArr ;
foreach($array as $index=>$eachMixVal){
if(is_array($eachMixVal)){
recursiveArrayShiftToRoot($eachMixVal);
}else{
$newArr[$index] = $eachMixVal;
}
}
}
recursiveArrayShiftToRoot(json_decode($json, true), $newArr);

How do I "trim" this JSON with PHP?

I have a JSON that's strangely formatted ...but it's the way I receive it. Because the arrays inside are huge, simply copying and pasting it takes a long time, so I'm wondering if there's a PHP way to do it.
The way I get it is like this:
{"count":459,"results":[{"title":"Something ....}],"params":{"limit..},"type":"Listing","pagination":{"..":5}}
But I want to get only the "results" array, basically the part of [{"title":"Something ....}]. How would I do that?
Do
$arr = json_decode(your_json, true);
If you ned it as JSON again, do
json_encode($arr['results']);
You can get to that part as follows:
$json = '{"count":459,"results":[{"title":"Something ...."}],"params":{"limit":".."},"type":"Listing","pagination":{"..":5}}';
$obj = json_decode($json);
echo $obj->results[0]->title;
Outputs:
Something ....
You have to decode your json. Be sure that the json is valid!
Your decoded json returns an object of type stdClass instead of an array!
See below the tested code:
$json = '{"count":459,"results":[{"title":"Something ...."}],"params":{"limit": "foo"},"type":"Listing","pagination":{"foo":5}}';
$decoded = json_decode($json);
So you can access array results from the object $decoded:
print_r($decoded->results);
But, in the array, there are objects, thus:
echo $decoded->results[0]->title; // Something ....

How to loop through this json decoded data in PHP?

I've have this list of products in JSON that needs to be decoded:
"[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]"
After I decode it in PHP with json_decode(), I have no idea what kind of structure the output is. I assumed that it would be an array, but after I ask for count() it says its "0". How can I loop through this data so that I get the attributes of each product on the list.
Thanks!
To convert json to an array use
json_decode($json, true);
You can use json_decode() It will convert your json into array.
e.g,
$json_array = json_decode($your_json_data); // convert to object array
$json_array = json_decode($your_json_data, true); // convert to array
Then you can loop array variable like,
foreach($json_array as $json){
echo $json['key']; // you can access your key value like this if result is array
echo $json->key; // you can access your key value like this if result is object
}
Try like following codes:
$json_string = '[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]';
$array = json_decode($json_string);
foreach ($array as $value)
{
echo $value->productId; // epIJp9
echo $value->name; // Product A
}
Get Count
echo count($array); // 2
Did you check the manual ?
http://www.php.net/manual/en/function.json-decode.php
Or just find some duplicates ?
How to convert JSON string to array
Use GOOGLE.
json_decode($json, true);
Second parameter. If it is true, it will return array.
You can try the code at php fiddle online, works for me
$list = '[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]';
$decoded_list = json_decode($list);
echo count($decoded_list);
print_r($decoded_list);

Implode JSON object

Below given, is my code:
$array=$_POST[number];
$jstring = json_decode($array,true);
$sa = "'".implode("','",$jstring)."'";
The error is given below.
Warning: implode() [function.implode]: Invalid arguments passed <root> on line <line no>
Number is a JSON object. Can someone Help me out? please. Thanks in Advance.
Edit:
Number is a JSON string. I need it to be comma separated. Number holds the phone numbers from a mobiles contact. I need each number to be used in an Sql Query.
Problem Fixed:
I fixed this problem. Sharing with others.
$array = $_POST[number];
$json = (array) json_decode($array,true);
$sa = "'" . implode(',', $json) . "'";
If you're having trouble debugging, use var_dump or even in combination with gettype() around the argument you're trying to implode. You never need to implode JSON objects, they are decoded perfectly find. Make sure you know the difference between CSV (Comma Separated Values) and JSON.
CSV:
Believe,it,or,not,I,am,CSV
Whereas JSON:
{"itbetrue":"ibeJSON"}
{"iam":["an","array","in","JSON"]}
If you're trying to get a JSON decoded array's values, use it like this:
$csv = implode(',', array_values($json));
Try this:
$json = $_POST['number']; // $json is a json string
$object = json_decode($json, JSON_FORCE_OBJECT); // stdClass => array
echo implode("','", $object); // This works if $object is not multiple array
make sure that the value $_POST[number] is coming as a json format before trying to decode it ... can u var_dump it and check

Reading multiple json values with php

I am trying to read certain values from a json string in php, I am able to do a simple json string with only one value such as
$json = '{"value":"somevalue"}';
Using this:
<?php
$json = '{"value":"somevalue"}';
$obj = json_decode(json_encode($json));
print $obj->{'value'};
?>
But when i try an get a value from the following json string it throws an error...
$json = '{"field": "title","rule": {"required": "true","minlength": "4","maxlength": "150" }}';
I validated the json on JSONlint but not sure how to access the values within this with php.
Thanks
You can try this:
$json = '{"field": "title","rule": {"required": "true","minlength": "4","maxlength": "150" }}';
//since $json is a valid json format you needn't encode and decode it again
$obj = json_decode($json);
print_r($obj->filed);
print_r($obj->rule);
You can pass true as a second parameter to json_decode() to get the results as an array
$my_arr = json_decode($json, true);
var_dump($my_arr);
Should help you. You can then step through the array as you would normally.
use var_dump to print out the object with all it's members and hierarchy. you should then be able to find the value you are looking for

Categories