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
Related
PHP NEWBIE
[PHP 7.4]
I am trying to refactor some old code.
GOAL: The two JSON must match.
Code snipppet 1: Old JSON code generated from php array
Code snippet 2: New JSON code generated from php array
Objective: Both must match, I am using php unit to compare them. For simplicity, I have removed the testing code.
PROBLEM: Extra set of square brackets, see image below.
I tried Using JSON_FORCE_OBJECT, which removes the square brackets, but introduces {... john: { "0": { "byEmail" ... " and ... "marie": { "1" { "byEmail" ...
(Naming wise: I have used John and marie, but these could be promotions, offers, packages, etc. so ignore the naming please)
SNIPPET 1 - php code
$body = [
"data" => [
"john" => [
"byEmail" => [
"status" => true,
"source" => "my-server",
],
"byPhoneCall" => [
"status" => true,
"source" => "my-server",
]
],
"marie" => [
"byEmail" => [
"status" => true,
"source" => "my-server",
],
"byPhoneCall" => [
"status" => true,
"source" => "my-server",
]
]
]
];
This gets converted to this JSON object:
// SNIPPET 1 - running json_encode()
{
"data": {
"john": {
"byEmail": {
"source": "my-server",
"status": true
},
"byPhoneCall": {
"source": "my-server",
"status": true
}
},
"marie": {
"byEmail": {
"source": "my-server",
"status": true
},
"byPhoneCall": {
"source": "my-server",
"status": true
}
}
}
}
SNIPPET 2:
I am creating this data structure dynamically now, because future requirement may have johnByPost, johnByFax, etc.:
//my-file-dynamic-generation.php
public function constructArray($johnByEmail=null, $johnByPhone=null, $marieByEmail=null, $marieByPhone=null) {
$body = [ "data" => ["john" => [], "marie" => []]];
if ($johnByEmail !== null) {
array_push($body["data"]["john"], $this->createKeyValuePair("byEmail", $johnByEmail));
}
if ($johnByPhone !== null) {
array_push($body["data"]["john"], $this->createKeyValuePair("byPhoneCall", $johnByPhone));
}
if ($marieByEmail !== null) {
array_push($body["data"]["marie"], $this->createKeyValuePair("byEmail", $marieByEmail));
}
if ($marieByPhone !== null) {
array_push($body["data"]["marie"], $this->createKeyValuePair("byPhoneCall", $marieByPhone));
}
return $body;
}
// HELPER func
function createKeyValuePair($title=null, $status=null, $source="my-server") {
return [
$title => [
"status" => $status,
"source" => $source,
]
];
}
JSON - OUTPUT
I have tried to use json_encode($data, JSON_FORCE_OBJECT)
That resulted me to get an extra key, which I don't want (I got .... [0] => 'marie' => ... [1] => 'john'
Appreciate reading this, thanks!
You are creating a new array inside the function createKeyValuePair() (probably to add the key). You could use the function the create the content only, and create the key inside the function constructArray() :
$body["data"]["john"]["byEmail"] = $this->createKeyValuePair($johnByEmail);
and the function :
function createKeyValuePair($status = null, $source = "my-server"): array
{
return [
"status" => $status,
"source" => $source,
];
}
This question already has an answer here:
php - converting from one json format to another
(1 answer)
Closed 1 year ago.
I've been trying to add a parent key "data" to a PHP $dataset json:
my $dataset json:
[
{
"id":"H",
"description": "Hello"
},
{
"id":"B",
"description":"Bye",
},
]
the final output must be
[
"data": {
{
"id":"H",
"description": "Hello"
},
{
"id":"B",
"description":"Bye",
},
},
]
Can you please help me? Thank you!
The easiest way is to decode to array and add the parent then encode again to json.
$output_json = json_encode(array("data" => json_decode($dataset)));
$data = [
'data' => $dataset,
'status' => true
];
return json_encode($data);
The syntax of JSON type is {key:vale}
your code should be like:
{
"data": [
{
"id":"H",
"description": "Hello"
},
{
"id":"B",
"description":"Bye",
},
],
}
Try this out:
$final_result = array('data' => $dataset)
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);
?>
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));
$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.