JSON encode multiplies arrays as single array - php

$array = array(
$this->_order->revenue_seller($value,$from,$to),
$this->_order->refund_seller($value,$from,$to),
$this->_order->customers_seller($value,$from,$to),
$this->_order->sales_seller($value,$from,$to)
);
$this->response($array,200);
I want the data to be be displayed as a single array, but as we can see, the output is begin displayed as array of arrays:
[
[
{
"min_amount":"2.00",
"max_amount":"2.00",
"avg_amount":"2.000000",
"total_revenue":"2.00"
}
],
[
{
"total_refund_amount":"1.00"
}
],
[
{
"created_at":"2013-03-24 15:04:35"
}
],
[
{
"quantity":"1"
}
]
]
How can I make the data appear as one single array?
Like this:
[
{
"day":"2013-03-19",
"min_amount":"0.00",
"max_amount":"0.00",
"avg_amount":"0.000000",
"total_revenue":"0.00",
"quantity" : "1",
"total_refunded_amount":null,
"created_at":"2013-03-24 15:04:35"
}]

If you are getting array return by all four function than use array_merge as,
$array = array_merge($this->_order->revenue_seller($value,$from,$to),
$this->_order-refund_seller($value,$from,$to),
$this->_order->customers_seller($value,$from,$to),
$this-_order->sales_seller($value,$from,$to));
$this->response($array,200);
DEMO.

Related

json_encode treats a single element array as object [duplicate]

This question already has answers here:
How to add square braces around subarray data inside of a json encoded string?
(3 answers)
Closed 6 months ago.
this is the json i have to produce
{
"email": "example#example.com",
"campaign": {
"campaignId": "p86zQ"
},
"customFieldValues": [
{
"customFieldId": "y8jnp",
"value": ["18-29"]
}
]
}
if i use
$data = [
"email" => $_POST['mail'],
"campaign" => [
"campaignId" => "4JIXJ"
],
"customFieldValues" => [
"customFieldId" => "y8jnp",
"value" => ["18-29"]
]
];
and i do json_encode($data)
value is an object, but it should be an array with a single element. Somehow json_encode treats it as an object. Can i force it to treat it as an array with a single element ?
Thanks in Advance
Adrian
At the moment, you have a single array with 2 elements, instead of an array with a single element of a sub-array. In order to get the json in the first section, you need to add another array level.
$data = [
"email" => $_POST['mail'],
"campaign" => [
"campaignId" => "4JIXJ"
],
"customFieldValues" => [
[
"customFieldId" => "y8jnp",
"value" => ["18-29"]
]
]
];
That will give you this:
{
"email": null,
"campaign": {
"campaignId": "4JIXJ"
},
"customFieldValues": [
{
"customFieldId": "y8jnp",
"value": ["18-29"]
}
]
}
if there is one single element in the array the json_encode will treat is as an object and the key of the object is the index of the array
to treat it as an array you can use array_values(<your_array>)

How to get value from an array?

I have this array
{
"findCompletedItemsResponse": [
{
"ack": [
"Success"
],
"version": [
"1.13.0"
],
"timestamp": [
"2018-12-16T18:27:26.221Z"
],
"searchResult": [
{
"#count": "3",
"item": [
{
"itemId": [
"263933812890"
],... continue
I am using this code to get "itemId"
for( $i = 0; $i<5; $i++ ) {
echo $itemid = $data2['findCompletedItemsResponse']['searchResult']['item'][$i]['itemId'];
}
But I am not able to get "itemId". How can I get itemId from this array.
It's also displaying a notice "Undefined index: searchResult"
Under findCompletedItemsResponse key You have simple array with numeric indexes, same for searchResult, so assuming that they both only contains one element:
$data2['findCompletedItemsResponse'][0]['searchResult'][0]['item'][$i]['itemId'];
Looks like this is JSON response, you probably need to json decode it:
json_decode($data2, true);
see if this helps

String into array

I have a string like:
{
"OperationResult": [
{
"CA::Read:PackageItems": {
"Read.PackageItem.RemoteBalanceAssigned": false,
"Read.PackageItem.CLSpvInfo": "1|-1#-9223372036854775000",
"PackageList":
[
"TopSim-4GSim1GBData",
"TopSim-ATBReactivation"
],
"PackageTypeList":
[
"optional-unsubscribed", "optional-unsubscribed"
],
"PackageFunctionalNameList":
[
"FreeUnits",
"AccumulationReward+MultipleThresholds"
],
"PackageSubStateList":
[
"",
""
],
"PackageEligibilityList":
[
true,
true
]
}
}]
}
I am trying to get it into array. but I want filter this string and only put PackageList":["xxxx-yyy","zzz-zzz"] and "PackageSubStateList":[TRUE,FALSE]}
Any thing in between should be filter out.
The resulted array should be like:
PackageList {
name: xxxx-yyy,
state: TRUE,
}
....
//The json posted in the question is invalid, assuming valid json gets used here afterwards:
$string = '{"OperationResult":[{"CA::Read:PackageItems":{"PackageList":["xxxx-yyy","zzz-zzz"],
"PackageTypeList":["optional-unsubscribed","optional-"optional-unsubscribed""],
"PackageFunctionalNameList":["FreeUnits","AccumulationReward+MultipleThresholds"],
"PackageSubStateList":[TRUE,FALSE]}';
$object = json_decode($string);
$wanted = $object['OperationResult']['CA::Read:PackageItems'];
$wanted should now contain what you need

Generate JSON for Google Charts using PHP

I'm following the guide at:
https://developers.google.com/chart/interactive/docs/php_example
They give a json snippet for a json example. How do yo build this one with php? Usually there is just converting arrays to json using json_encode() but this time it seems like you need an object aswell. Can anyone clarify this?
The json snippet:
{
"cols": [
{"id":"","label":"Topping","pattern":"","type":"string"},
{"id":"","label":"Slices","pattern":"","type":"number"}
],
"rows": [
{"c":[{"v":"Mushrooms","f":null},{"v":3,"f":null}]},
{"c":[{"v":"Onions","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Olives","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Zucchini","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Pepperoni","f":null},{"v":2,"f":null}]}
]
}
What I have so far:
$obj = new stdClass();
$obj->cols= array(
array("id"=>"", "label"=>"Topping", "pattern"=>"", "type"=>"string"),
array("id"=>"", "label"=>"Slices", "pattern"=>"", "type"=>"string"));
$obj->rows = array(
array()
);
echo json_encode($obj);
Is there anyone that knows how to complete this php representation?
Edit:
My echo outputs:
{"cols":[{"id":"","label":"Topping","pattern":"","type":"string"},{"id":"","label":"Slices","pattern":"","type":"string"}],"rows":[[]]}
PHP associative arrays will converts to objects in JSON, so stdClass is not needed. You already got 80% of the structure so here are a few pointers:
$data = [
'cols' => [],
'rows' => [],
];
will result in :
{
'cols': [],
'rows': [],
}
In order to get JSON arrays, don't give keys to the values:
$data = [
'c' => [
[ // <- no key here
'v' => 'Mushroom',
'f' => null
],
[ // <- no key here
'v' => '3',
'f' => null
],
],
// ...
];
will give you a data row:
{
"c": [ // <- we got an actual array here because there was no key
{
"v":"Mushrooms",
"f":null
},
{
"v":3,
"f":null
}
]
}
This code should work:
<?php
$obj = array("cols"=>array(
array("id"=>"", "label"=>"Topping", "pattern"=>"", "type"=>"string"),
array("id"=>"", "label"=>"Slices", "pattern"=>"", "type"=>"string")),
"rows"=>array(
array("c"=>array(array("v"=>"Mushrooms", "f"=>null), array("v"=>3, "f"=>null))),
array("c"=>array(array("v"=>"Onions", "f"=>null), array("v"=>1, "f"=>null))),
array("c"=>array(array("v"=>"Olives", "f"=>null), array("v"=>1, "f"=>null))),
array("c"=>array(array("v"=>"Zucchini", "f"=>null), array("v"=>1, "f"=>null))),
array("c"=>array(array("v"=>"Pepperoni", "f"=>null), array("v"=>2, "f"=>null))),
)
);
echo json_encode($obj);
?>

How to create a json file using an array in PHP

I have the following php script in which I attempt to write a JSON file with contents of an array:
$name = "TEST";
$type = "TEST";
$price = "TEST";
$upload_info = array();
$upload_info = array('name'=>$name,'type'=>$type,'price'=>$price);
$temp_array = json_decode(file_get_contents('upload.json'));
array_push($temp_array, $upload_info);
file_put_contents('items.json', json_encode($temp_array));
$json = json_encode($upload_info);
$file = "items.json";
file_put_contents($file, $json);
This will add the following line to items.json:
{"name":"TEST","type":"TEST","price":"TEST"}
It also gives this error:
PHP Warning: array_push() expects parameter 1 to be array, null given in /var/www/html/list/add.php on line 13
What I would ideally like to do is to have my script add to specific parts of a json file that looks something like this:
{
"GC": [
{ "Name":"Thing" , "Price":"??" , "Link":"www.google.com" },
{ "Name":"Thing" , "Price":"??" , "Link":"www.google.com" }
]
"0": [
]
"10": [
]
"20": [
]
"30": [
]
"40": [
]
"50": [
]
"60": [
]
"70": [
]
"80": [
]
"90": [
]
"100": [
]
"200": [
]
"300": [
]
"400": [
]
"500": [
]
}
Each one of those arrays would hold items (similar to the GC array) after they have been added with add.php. Is this possible? If so, how would I do it?
Is it possible to select specific parts of the json where I would want to add the entries? Is there an easier way to do this? I am just looking for a solution to storing my data without using a database.
you need to use second parameter true, of json_decode() to get array result, like:
$temp_array = json_decode(file_get_contents('upload.json'), true);
//get the needed values from $temp_array
//create a new array out of it
file_put_contents('items.json', json_encode($your_final_array));

Categories