How to create a json file using an array in PHP - 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));

Related

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);
?>

Creating a JSON object from multidimensional array stored as string

I'm trying to generate a JSON object using PHP to be passed to the client using data that is already stored in MySQL database.
The database contains a list of multipolygon coordinates like below in a single text field:
[
[
[
[
104.39209000000005,
-4.850154
],
[
108.17138687500005,
-3.721745195827911
],
[
112.12646500000005,
-1.274309
],
[
103.02978499999995,
-3.579213
]
]
]
]
When I try to generate a JSON object using json_encode I get the following:
{
"coordinates": "[[[[104.39209000000005,-4.850154],[108.17138687500005,-3.721745195827911],[112.12646500000005,-1.274309],[103.02978499999995,-3.579213]]]]"
}
And because of the quotes around the coordinates themselves, they are not recognised as JSON object by JavaScript.
I've tried to explode the coordinate string and then put it back together manually but it still needs a lot of hacks to get it working.
Any help in getting this to output as a an actual JSON object in PHP would be much appreciated.
I'm trying to get to this:
{
"coordinates": [
[
[
[
104.39209000000005,
-4.850154
],
[
108.17138687500005,
-3.721745195827911
],
[
112.12646500000005,
-1.274309
],
[
103.02978499999995,
-3.579213
]
]
]
]
}
It's pretty jerry-rigged, but you could do this:
$string = json_encode( $database_value ); // same as you're using now
$string = str_replace( '"', '', $string ); // get rid of the quotes
// wrap them back around 'coordinates'
$string = str_replace( 'coordinates', '"coordinates"', $string );
Simply use json_decode before json_encode, like this:
// This comes from the database, of course
$coords = '[[[[104.39209000000005,-4.850154],[108.17138687500005,-3.721745195827911],[112.12646500000005,-1.274309],[103.02978499999995,-3.579213]]]]';
echo json_encode(array(
'coordinates' => json_decode($coords)
));
This will output nested arrays exactly as you desire:
{"coordinates":[[[[104.39209,-4.850154],[108.171386875,-3.7217451958279],[112.126465,-1.274309],[103.029785,-3.579213]]]]}

JSON encode multiplies arrays as single array

$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.

Categories