Php json_decode parsing read child value - php

I am parsing a JSON being posted from another website and one of the nodes has a child.
$inputJSON = file_get_contents('php://input');
$input= json_decode( $inputJSON); //convert JSON into object
$order_number = $input->{'order_no'};
$name = $input->{'name'};
$street_address = $input->{'address_1'};
$city =$input->{'city'};
$state = $input->{'region'} ;
$zip = $input->{'postal_code'};
I am being able to read all the values. However, the product section has the format
<items>
<product_code></product_code>
<product_name></product_name>
</items>
I am trying to read it as
$product_id = $input->{'items'}{'product_code'};
$product_description = $input->{'items'}{'product_name'};
But I am getting no data in my variables. What is the correct syntax?
Thanks.
Edit: The JSON output
object(stdClass)#1 (20) {
["test_order"]=>
string(1) "Y"
["shop_no"]=>
string(6) "142319"
["order_no"]=>
string(12) "TU5495467701"
string(5) "Smith"
["city"]=>
string(5) "Bosei"
["postal_code"]=>
string(6) "123456"
["order_total"]=>
string(5) "39.00"
["country"]=>
string(2) "HK"
["telephone"]=>
string(8) "12345678"
["pay_source"]=>
string(2) "CC"
["base_currency"]=>
string(3) "USD"
["items"]=>
array(1) {
[0]=>
object(stdClass)#2 (9) {
["product_price"]=>
string(5) "39.00"
["product_name"]=>
string(12) "Abcd Product"
["product_code"]=>
string(8) "142319-1"
}
}
["first_name"]=>
string(4) "John"
}

As you wrote:
["items"]=>
array(1) {
[0]=>
object(stdClass)#2 (9) {
["product_price"]=>
string(5) "39.00"
["product_name"]=>
string(12) "Abcd Product"
["product_code"]=>
string(8) "142319-1"
}
}
The items element is an array, contains multiple objects, so you must use this syntax:
$product_id = $input->items[0]->product_code;
$product_description = $input->items[0]->product_name;
And, If the items are more than one, you should use a loop:
for ($i = 0; $i < count($input->items); $i++) {
$product_id = $input->items[$i]->product_code;
$product_description = $input->items[$i]->product_name;
}

$product_id = $input->items[0]->product_code;
More likely though you will want to loop through $input->items instead of directly accessing just the first index.

I'm not shure but I think you can use it as an array and do something like this:
$product_id = $input['items']['product_code'];
$product_description = $input['items']['product_name'];

In php json_decode returns an array. So you should be able to access it simply as you access array values.
$product_id = $input['items']['product_code'];

Related

How can I filter data from my array php?

I am really struggling filtering my data.I know how to access parts of the array but am struggling on how to filter. I know how to do it in SQL SUM & count) but not when it comes to PHP arrays please help.
I need to filter some of my data stored in the variable $res.
I need to see how many times each 'REF' appears & total 'LCL_D_CBM' for each ref all of this where the "TERR" is equal to "TERR1".
foreach ($res as $res1){
if ($res1["TERR"] == "TERR1"){
//the individual ref
//$res1['REF'];
// the coutn of how many times each ref appears
//echo count($res1['REF']);
//sum
//echo array_sum($res1['LCL_D_CBM']);
}
}
need result to be like -
CEA
3
2561
CEF
456
135
var_dump($res); gives me below
array(350) {
[0]=> array(7) { [0]=> string(3) "CEA" ["REF"]=> string(3) "CEA" [1]=> string(5) "1.080" ["LCL_D_CBM"]=> string(5) "1.080" [2]=> string(3) "WF2" ["AREA_CODE"]=> string(3) "WF2" ["TERR"]=> string(5) "TERR1" }
[1]=> array(7) { [0]=> string(3) "CEA" ["REF"]=> string(3) "CEA" [1]=> string(5) "2.000" ["LCL_D_CBM"]=> string(5) "2.000" [2]=> string(4) "HU13" ["AREA_CODE"]=> string(4) "HU13" ["TERR"]=> string(5) "TERR1" }
[2]=> array(7) { [0]=> string(3) "CEF" ["REF"]=> string(3) "CEA" [1]=> string(5) "2.448" ["LCL_D_CBM"]=> string(5) "2.448" [2]=> string(4) "TW16" ["AREA_CODE"]=> string(4) "TW16" ["TERR"]=> string(5) "TERR2" } ..... etc
You can solve it like this. Not a pretty solution, but should do the work. (I did not test this, so it might contain a spelling error or something):
$sum_lcl = 0;
$unique_refs = array();
foreach ($res as $res1){
if (!array_key_exists($res1['REF'], $unique_refs)) {
$unique_refs[$res1['REF']] = array();
}
$unique_refs[$res1['REF']]['SUM'] = ( array_key_exists('SUM', $unique_refs[$res1['REF']]) ) ? ( intval( $unique_refs[$res1['REF']]['SUM'] ) + 1 ) : 1;
$unique_refs[$res1['REF']]['LCL_SUM'] = ( array_key_exists('LCL_SUM', $unique_refs[$res1['REF']]) ) ? ( floatval( $unique_refs[$res1['REF']]['LCL_SUM'] ) + floatval( $res1['LCL_D_CBM'] ) ) : 1;
}
foreach( $unique_refs AS $unique => $data ){
$title = $unique;
$sum = $data['SUM'];
$lcl_sum = $data['LCL_SUM'];
echo "{$title}<br />{$sum}<br />{$lcl_sum}";
}

Return an array from a function

I am using the PHP Simple HTML DOM Parser to scrape some results from a page.
At the moment I am having a problem with the function as it is not returning the array "$result".
Any help would be greatly appreciated :)
The result of the array:
array(1) { [0]=> array(6) { ["itemid"]=> string(6) "123456" ["title"]=> string(21) "XXX Prod1" ["unit"]=> string(6) "500ml " ["price"]=> string(4) "2.59" } [1]=> array(6) { ["itemid"]=> string(6) "123457" ["title"]=> string(27) "XXX Prod2" ["unit"]=> string(6) "500ml " ["price"]=> string(5) "10.49" }
Code in question:
function parseItems($html) {
foreach($html->find('div.product-stamp-inner') as $content) { //Finds each individual product on page and extracts its details and stores it into its own array
$detail['itemid'] = filter_var($content->find('a.product-title-link', 0)->href, FILTER_SANITIZE_NUMBER_FLOAT);
$detail['title'] = $content->find('span.title', 0)->plaintext;
$detail['unit'] = $content->find('span.unit-size', 0)->plaintext;
$detail['price'] = filter_var($content->find('span.price', 0)->plaintext, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND);
$result[] = $detail; //Puts all individual product arrays into one large array
}
//var_dump($result); --Testing purposes
return $result;
}
I guess what you have a piece of code like so
parseItems($html);
When it should be the following because it is returning a variable and needs a variable to hold its returning result
$retval = parseItems($html);

Converting Json String into PHP array then using php array

Im new to json & php and I'm having some issues with json into php string
My json string looks like this
{"status":"OK","cards":
[{"id":100001,"name":"batman","image":11111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-08-15T11:37:07Z"},
{"id":100002,"name":"superman","image":111111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-08-15T12:30:09Z"},
{"id":100003,"name":"catwoman","image":1111111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-08-15T12:39:42Z"},
{"id":100004,"name":"bane","image":1111111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-09-08T12:56:04Z"}
]}
So Far i have created my string
$json_raw = '{"status":"OK","cards": [{"id":100001,"name": .....
Decoded the json
$arr = json_decode($json_raw, TRUE);
I var_dump($arr);
then it returns
array(2) { ["status"]=> string(2) "OK" ["cards"]=> array(4) { [0]=> array(8) { ["id"]=> int(100001) ["name"]=> string(6) "batman" ["image"]=> int(11111) ["size"]=> int(75) ["region_id"]=> int(1) ["locked"]=> bool(false) ["status"]=> string(6) "active" ["created_at"]=> string(20) "2013-08-15T11:37:07Z" } [1]=> array(8) { ["id"]=> int(100002) ["name"]=> string(8) "superman" ["image"]=> int(111111) ["size"]=> int(75) ["region_id"]=> int(1) ["locked"]=> bool(false) ["status"]=> string(6) "active" ["created_at"]=> string(20) "2013-08-15T12:30:09Z" } [2]=> array(8) { ["id"]=> int(100003) ["name"]=> string(8) "catwoman" ["image"]=> int(1111111) ["size"]=> int(75) ["region_id"]=> int(1) ["locked"]=> bool(false) ["status"]=> string(6) "active" ["created_at"]=> string(20) "2013-08-15T12:39:42Z" } [3]=> array(8) { ["id"]=> int(100004) ["name"]=> string(4) "bane" ["image"]=> int(1111111) ["size"]=> int(75) ["region_id"]=> int(1) ["locked"]=> bool(false) ["status"]=> string(6) "active" ["created_at"]=> string(20) "2013-09-08T12:56:04Z" } } }
Now all I want to do is be able to use this data
e.g if name = batman then
I know this is a stupid question but I am struggling :(
Thank in Advance
json_decode() with TRUE as second parameter gives you an associative array. You need to access the correct index to do what you want.
To list the complete associative array with nice formatting, you can do:
echo '<pre>', print_r($arr), '</pre>';
Now, to access the name in your array:
$man = $arr['cards'][0]['name'];
To check if it's Batman (yay!):
if( isset($man) && $man == 'batman' ) {
# code ...
}
For getting the name of all similar names:
$man = $json['cards']['0']['name'];
for ($i=0; $i < count($json['cards']); $i++) {
echo $json['cards'][$i]['name']."\n";
}
See it live!
when you got the array
$arr = json_decode($json_raw, TRUE);
then check if cards key exist
if(array_key_exists('cards', $arr)){
foreach($arr['cards'] as $key=>$val){
echo $key; ///name, id..
echo $val; /// batman,...
if($key == 'name' && $val =='batman'){
//-------do your stuff
}
}
}
Try with:
$cards = $arr['cards'];
foreach($cards as $card) {
if($card['name'] == 'batman') echo 'Hello batman!';
}
EDIT:
Ok, so this worked for me using code above, try it yourself if you want:
<?php
$json_raw = '{"status":"OK","cards":
[{"id":100001,"name":"batman","image":11111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-08-15T11:37:07Z"},
{"id":100002,"name":"superman","image":111111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-08-15T12:30:09Z"},
{"id":100003,"name":"catwoman","image":1111111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-08-15T12:39:42Z"},
{"id":100004,"name":"bane","image":1111111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-09-08T12:56:04Z"}
]}';
$arr = json_decode($json_raw, TRUE);
$cards = $arr['cards'];
foreach($cards as $card) {
if($card['name'] == 'batman') echo 'Hello batman!';
}
?>

Get value in PHP from JSON

I need to get the objects information for "label", "name" where value=true in a PHP variable and not were value=false.
How is this done with this JSON array?
If I make a var_dump of the JSON I get this:
array(8) {
[0]=>
object(stdClass)#8 (3) {
["label"]=>
string(4) "Name"
["name"]=>
string(7) "txtName"
["value"]=>
bool(true)
}
[1]=>
object(stdClass)#9 (3) {
["label"]=>
string(6) "E-mail"
["name"]=>
string(8) "txtEmail"
["value"]=>
bool(true)
}
[2]=>
object(stdClass)#10 (3) {
["label"]=>
string(12) "Phone Number"
["name"]=>
string(8) "txtPhone"
["value"]=>
bool(false)
}
[3]=>
object(stdClass)#11 (3) {
["label"]=>
string(19) "Mobile Phone Number"
["name"]=>
string(14) "txtMobilePhone"
["value"]=>
bool(false)
}
}
$arr = array();
$i = 0;
foreach($json as $key => $items) {
if($items->value == true) {
$arr[$i]['label'] = $items->label;
$arr[$i]['name'] = $items->name;
$i++;
}
}
You can decode it as an object or an array, in this example I use an array.
First you want to take the JSON encoded information and decode it into a PHP array, you can use json_decode() for this:
$data = json_decode($thejson,true);
//the Boolean argument is to have the function return an array rather than an object
Then you can loop through it as you would a normal array, and build a new array containing only elements where 'value' matches your needs:
foreach($data as $item) {
if($item['value'] == true) {
$result[] = $item;
}
}
You then have the array
$result
at your disposal.
Simplification of the suggestions proposed by users JohnnyFaldo and som:
$data = json_decode($thejson, true);
$result = array_filter($data, function($row) {
return $row['value'] == true;
});

PHP & JSON: How can I get a value from where another value equals xyz?

I'm receiving a JSON and trying to interpret some values using PHP.
Example snippet from a JSON dump:
["11811"]=>
object(stdClass)#15 (11) {
["parent_area"]=>
NULL
["generation_high"]=>
int(19)
["all_names"]=>
object(stdClass)#16 (0) {
}
["id"]=>
int(11811)
["codes"]=>
object(stdClass)#17 (3) {
["ons"]=>
string(2) "08"
["gss"]=>
string(9) "E15000008"
["unit_id"]=>
string(5) "41421"
}
["name"]=>
string(10) "South East"
["country"]=>
string(1) "E"
["type_name"]=>
string(15) "European region"
["generation_low"]=>
int(1)
["country_name"]=>
string(7) "England"
["type"]=>
string(3) "EUR"
}
As there is lots of (nested) data, I need to obtain the value of ["name"] where ["type_name"] == 'European region'.
Thanks.
You could use array_filter()
$data_array = array(...);
function is_european($data) {
return $data->type_name == 'European region';
}
$filtered = array_filter($data_array,'is_european');
And then use filtered array to obtain values.
Maybe a better way would be to use JsonPath, like this, assuming your array is a result of decoding JSON (object):
$names = jsonPath($data_object, "$.[?(#['type_name'] == 'European region')].name");
Haven't tried this myself, it may need a bit of correction.
Try this:
<?php
$json = JSON_decode(str,true);
$arr = Array();
foreach($json as $f) {
/* eg. $f = $json["11811"] */
if($f['type_name'] == 'European region') {
$arr[] = $f['name'];
}
}
?>

Categories