How to parse Json data in php? - php

[{"name":"se","value":"test1"},{"name":"model","value":"test2"},{"name":"filter_preference","value":"test3"},{"name":"seved","value":"test4"}]
I have json, and I would like to parse it, and to get for "segment" => "test1"
and so on.
i have done this
$json2= json_encode($loadFilter);
$json2 = json_decode($json2, true);
foreach ($json2->$key as $value)
{
echo $key ."=>".$value;
}
always getting Invalid argument supplied for foreach() !!!
I am doing it WP ajax callback.

Your foreach syntax is wrong to access the $key.
foreach ($json2 as $key => $value) {
echo $key ."=>".$value;
}
Edit from your comments:
You didn't give the "real" format in your question, your array is contained in 'filter_preference', so you have to iterate over $json2['filter_preference'].
foreach ($json2['filter_preference'] as $key => $value) {
echo $key ."=>".$value;
}

you need to map key value for sub array.
try this:
foreach ($json2 as $key=>$value)
{
echo $key ."=>".$value;
}

One odd suggestion here:
If you want to use array for this then you can convert object to array using following code:
function objectToArray($d) {
if (is_object($d)) {
// Gets the properties of the given object
// with get_object_vars function
$d = get_object_vars($d);
}
if (is_array($d)) {
/*
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
return array_map(__FUNCTION__, $d);
}
else {
// Return array
return $d;
}
}
$array_new = objectToArray($json2);
http://wonderphp.wordpress.com/2014/03/20/convert-object-to-array-and-vice-versa/

Related

How to create a dynamic JSON array in PHP using multiple for eaches?

I need to generate a JSON Object and push it to a JSON object array using PHP.
This is my code.
public function getJSONData()
{
$csv = $this->getCsvData();
$finalArray = array();
// First foreach to iterate the data array.
foreach ($csv["data"] as $key => $value) {
// Second foreach to iterate the headlines array.
$newArray = array();
foreach ($csv["headlines"] as $index => $headline) {
// $newArray[$key]->$csv["headlines"] = $value;
// print_r($headline);
// print_r($value[$index]);
// echo " ";
array_push($newArray, array($headline => $value[$index]));
}
echo json_encode($newArray);
echo "<br>";
array_push($finalArray, json_encode($newArray));
}
// dd($finalArray);
}
From this code, I'm getting the following response.
[{"ID":12348},{"Status":1},{"Manufacturere_ID":101},{"Famiy_matchcode":"101-iphone-11"},{"Name":"iPhone 11"},{"Price":639.95}]
[{"ID":12348},{"Status":1},{"Manufacturere_ID":101},{"Famiy_matchcode":"101-iphone-11"},{"Name":"iPhone 11"},{"Price":509.95}]
[{"ID":12348},{"Status":1},{"Manufacturere_ID":101},{"Famiy_matchcode":"101-iphone-11"},{"Name":"iPhone 11"},{"Price":349.95}]
[{"ID":12349},{"Status":1},{"Manufacturere_ID":101},{"Famiy_matchcode":"101-iphone-11"},{"Name":"iPhone 11"},{"Price":639.95}]
[{"ID":12349},{"Status":1},{"Manufacturere_ID":101},{"Famiy_matchcode":"101-iphone-11"},{"Name":"iPhone 11"},{"Price":509.95}]
[{"ID":12349},{"Status":1},{"Manufacturere_ID":101},{"Famiy_matchcode":"101-iphone-11"},{"Name":"iPhone 11"},{"Price":349.95}]
[{"ID":12350},{"Status":1},{"Manufacturere_ID":101},{"Famiy_matchcode":"101-iphone-11"},{"Name":"iPhone 11"},{"Price":639.95}]
[{"ID":12350},{"Status":1},{"Manufacturere_ID":101},{"Famiy_matchcode":"101-iphone-11"},{"Name":"iPhone 11"},{"Price":509.95}]
But it is not a valid JSON and I really need to get an output like this:
[{"ID":12348,"Status":1,"Manufacturere_ID":101,"Famiy_matchcode":"101-iphone-11","Name":"iPhone 11","Price":639.95}, {"ID":12348,"Status":1,"Manufacturere_ID":101,"Famiy_matchcode":"101-iphone-11","Name":"iPhone 11","Price":509.95}]
This is a standard JSON object array.
In my code, I'm using array_push($newArray, array($headline => $value[$index])); to generate the array and take it as JSON.
Please help me on this.
You seem to be creating arrays and adding json data in several places, build the data as a normal array and then encode the result...
// Foreach to iterate the data array.
foreach ($csv["data"] as $key => $value) {
// Combine headers with data and add to final result
$finalArray[] = array_combine($csv["headlines"], $value);
}
echo json_encode($finalArray);

json structure difference after edits

I have json string that I have to edit and then transform back to json. But unfortunately I can't really restore the json structure.
The structure of the original json string ($json):
"[{"Language":{"0":"EN"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}},
{"Language":{"0":"DE"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}},
{"Language":{"0":"FR"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}}]"
The structure I get after my edits ($newJson):
"{"0":{"Language":{"0":"EN"},"Text":{"0":"yyy"},"ContentType":{"0":"PlainText"}},
"1":{"Language":{"0":"DE"},"Text":{"0":"yyy"},"ContentType":{"0":"PlainText"}},
"2":{"Language":{"0":"FR"},"Text":{"0":"yyy"},"ContentType":{"0":"PlainText"}}}"
Here is what I do with my edits:
$jsonArray = object_to_array(json_decode($json));
$editedJsonArray = someLoopStuff($jsonArray);
$newJson = json_encode(array_to_object(($editedJsonArray)));
function object_to_array($obj) {
if(is_object($obj)) $obj = (array) $obj;
if(is_array($obj)) {
$new = array();
foreach($obj as $key => $val) {
$new[$key] = $this->object_to_array($val);
}
}
else $new = $obj;
return $new;
}
function array_to_object($a) {
if (is_array($a) ) {
foreach($a as $k => $v) {
$a[$k] = $this->array_to_object($v);
}
return (object) $a;
}
return $a;
}
Do you have an idea how I could get the same structure as the original json?
Use arrays instead of objects. Pass true to json_decode() as second argument and then do your stuff on arrays.
$jsonArray = json_decode($json, true);
Then just make your operation in loop on $jsonArray and simply use json_encode() without any additional work.
To achieve exactly same output as you have on input you need to cast subarrays on objects:
$jsonArray = json_decode('[{"Language":{"0":"EN"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}},{"Language":{"0":"DE"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}},{"Language":{"0":"FR"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}}]', true);
foreach ($jsonArray as &$item) {
foreach ($item as &$val) {
$val = (object) $val;
}
unset($val);
}
unset($item);
var_dump(json_encode($jsonArray));
Output:
string(226) "[{"Language":{"0":"EN"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}},{"Language":{"0":"DE"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}},{"Language":{"0":"FR"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}}]"
What if you would try to avoid using functions object_to_array and array_to_object. In the encoding part it is not necessary, because json_encode can handle objects or arrays. In the first part json_decode can be called with second optional parameter set to true to produce array instead of object. See PHP manual.

Accessing Certain JSON Elements

How would I go about accessing these elements from a Shopify JSON in PHP
JSON:
{
"orders":[
{ "note_attributes":[
{
"name":"field1",
"value":"xxxxxxxxxxxx"
},
{
"name":"field2",
"value":"xxxxxx"
},
{
"name":"field3",
"value":"xxxxxx"
}
],
This is just snippet of the object. How would I access each value and assign it to the name? Eg this $req['account_id'] would equal the value for that name tag. This is how am trying to do it but it's not working:
foreach ($order['note_attributes'] as $attributes) {
$req = array();
$req[$attributes->name] = $attributes[$attributes->value];
}
I would then like to echo $req['account_id'] and that would = xxxxxxxxx#gmail.com but it's not working any suggestions or fixes?
When iterating over Objects properties, one approach is to use (as you have) foreach
// accessing property
foreach ($objects as $object) {
echo $object->property;
}
// accessing key-value pair
foreach ($object as $key => $value) {
echo "$key => $value\n";
}
An example:
$attributes = array();
.
.
foreach($note_attributes as $note_attribute) {
$key = $note_attribute['name'];
$value = $note_attribute['value'];
$attributes[$key] = $value;
}
The structure should be in key-value pairs. ie.
attributes [
"account1234" => "abc#xxx.com",
"account_password" => "asdasdasd"
]
Hope this helps.
Update: as Roopendra mentioned, json_decode() with a TRUE flag with return an associative array, else stdClass.

how can i get multidimensional array values using foreach?

I want to use a multidimensional array in different functions.so i am making it as a global variable(array).i created a multidimensional array and made it as global to access in different function.now how can i get the values from it using foreach loop?
here is my code
$test=array(
array(
"input1"=>"v1",
"input2"=>"v2"),
array(
"input3"=>"v3",
"input4"=>"v4")
);
class testing
{
function testp()
{
global $test;
foreach($test as $key => $value)
{
echo $value;
}
var_dump($test);
echo is_array($test);
}
}
$obj = new testing();
$obj->testp();
i used is_array and var_dump to confirm whether its an array.
all are fine
and its shwoing Error suppression ignored. now how can i get the values from it?
It is array of arrays, what works for top order array, works further as well:
foreach($test as $key => $value)
{
foreach($value as $k => $v){
echo $v;
}
}
This will echo your values v1, v2, v3, v4 one after another.
More general answer:
public function visitArray($test)
{
foreach($test as $key=>$value)
{
if(is_array($value))
{
visitArray($value);
}
else
{
echo $value;
}
}
}
Edit
Don't know why you're looping over keys and values, if key isn't took into account
More easy & simple way to access array values within a array.
foreach($test as $array_value){
if(is_array($array_value)) {
foreach ($array_value as $value) {
echo $value.'<br>';
}
}
}

Do foreach on a object in php

How do i perform foreach on a object . I wish to format the result that i get in my ci query
foreach ($CIResult as $key => $value) {
$CIResult -> $key = MyCustomFunction($value);
}
EDIT
I want CIResult to stay as a object only
foreach ($CIResult as $key => &$value) {
$value = MyCustomFunction($value);
}
It's important to note that this will only work on public properties of your object.
You can always cast an object to an array.
foreach ($CIResult as &$object) //by reference
{
$object->property = $new_value;
}
Is this what you want ?
foreach ($CIResult as $ciObj) {
// Access object properties like
$ciObj->property_name = format_name($ciObj->property_name);
}
Can you please, be more explicit on what you want to format ?
foreach((array)$CIResult as $key => $value)
$CIResult->$key = MyCustomFunction($value);

Categories