PHP How to get a particular JSON values/parameter - php

This is my JSON Response came from an URL API. I use GuzzleHttp\Client and json_decode() inorder to manage.
[{
"INDEX_ID": "0",
"NOTES": "0; Farming"
},
{
"INDEX_ID": "1",
"NOTES": "Fruit Name; List of Fruits;"
},
{
"INDEX_ID": "2",
"NOTES": "Apple"
},
{
"INDEX_ID": "3",
"NOTES": "Orange"
},
{
"INDEX_ID": "4",
"NOTES": "Grapes"
},
{
"INDEX_ID": "5",
"NOTES": "Mango"
},
{
"INDEX_ID": "6",
"NOTES": "Animal Name; List of Animal;"
},
{
"INDEX_ID": "7",
"NOTES": "Pig"
},
{
"INDEX_ID": "8",
"NOTES": "Goat"
},
{
"INDEX_ID": "9",
"NOTES": "Cow"
}]
But I only need to save list of Fruits in my logfile. Can someone help me how to exclude the other json parameters and get only the particular json parameters using foreach loop or any method inorder to get that result.
I just want it to be like this:
[
{
"NOTE_NO." : "001",
"CATEGORY" : "FRUITS",
"LISTS_TO_BUY" : [
{
"FRUITS": "Apple"
},
{
"FRUITS": "Orange"
},
{
"FRUITS": "Grapes"
},
{
"FRUITS": "Mango"
}
]
}
]
He're my codes so far:
$response_body = json_decode($json_response, true);
$json_new_param = [];
foreach ($response_body as $value) {
$json_new_param[] = [
'FRUITS' => $value['NOTES']
];
}
$header = [
[
'NOTE_NO.' => '001',
'CATEGORY' => 'FRUITS',
'LISTS_TO_BUY' => $json_new_param
]
];
echo json_encode($header);
$json_response is the response given above.

You might use array_reduce to return an array where the key will be the first word from the value using implode which has this structure: "NOTES": "Fruit Name; List of Fruits;". The key for this would then be "Fruits".
During the array_reduce keep track of the current key using a variable $currKey
At the end you could then get the data by using "FRUIT" (Which is the first word) as the array key: $response_body["FRUIT"]
$response_body = json_decode($json_response, true);
$currKey = "0";
$response_body = array_reduce($response_body, function ($carry, $item) use (&$currKey){
if (strpos($item['NOTES'], 'Name; List') !== false) {
$currKey = strtoupper(explode(" ", $item["NOTES"], 2)[0]);
return $carry;
}
$carry[$currKey][] = ["FRUITS" => $item["NOTES"]];
return $carry;
});
$result = [
[
"NOTE_NO" => "001",
"CATEGORY" => ($name = "FRUITS"),
"LISTS_TO_BUY" => $response_body["FRUIT"]
]
];
echo json_encode($result, JSON_PRETTY_PRINT);
That will result in:
[
{
"NOTE_NO": "001",
"CATEGORY": "FRUITS",
"LISTS_TO_BUY": [
{
"FRUITS": "Apple"
},
{
"FRUITS": "Orange"
},
{
"FRUITS": "Grapes"
},
{
"FRUITS": "Mango"
}
]
}
]
Demo

Try this code .
$json_new_param = [];
$fruitFlag = false;
foreach ($response_body as $value) {
if(strpos($value['NOTES'],'Fruit Name') !== false){
$fruitFlag = true;
continue;
}
if(strpos($value['NOTES'],'Animal Name') !== false){
$fruitFlag = false;
}
if($fruitFlag == true){
$json_new_param[] = [
'FRUITS' => $value['NOTES']
];
}
}
echo json_encode($json_new_param, JSON_PRETTY_PRINT);

Related

Format the json encode just like on laravel php

Supposed I have a query that gets the image from a certain tweet
[
{
"pic": "/upload/15680712995mb.jpg",
"tweet_id": "48"
},
{
"pic": "/upload/1568071299test.PNG",
"tweet_id": "48"
},
{
"pic": "/upload/1568015310test.PNG",
"tweet_id": "47"
}
]
And I have a result also from a query that gets all of the tweet
[
{
"id": "48",
"tweet": "test",
},
{
"id": "47",
"tweet": "test tweet",
},
{
"id": "45",
"tweet": "test tweet 3",
}
]
How can I format the result like this (Just like on laravel)
[
{
"id": "48",
"tweet": "test",
"pics": [
[
"/upload/15680712995mb.jpg"
],
[
"/upload/1568071299test.PNG"
],
]
},
{
"id": "47",
"tweet": "test tweet",
"pics" : [
[
"/upload/1568015310test.PNG"
]
]
},
{
"id": "45",
"tweet": "test tweet 3",
"pics" : []
}
]
And this is my simplified code
public function getTweets()
{
$pics = $this->model->getPics();
$aTweets = $this->model->getTweets();
$map = [];
$props = [];
foreach ($aTweets as $sTweet) {
$map['id'] = $sTweet['id'];
$map['tweet'] = $sTweet['tweet'];
foreach ($pics as $pic) {
if ($pic['id'] === $sTweet['tweet_id']) {
$map['pics'] = [$pic['pic']];
}
}
$props[] = $map;
}
return $props;
}
but it just gives me the following output
{
"id": "48",
"tweet": "test",
"pics": [
"/upload/1568015310test.PNG"
]
},
{
"id": "47",
"tweet": "test tweet",
"pics": [
"/upload/1568015310test.PNG"
]
},
Any idea how can I format the result. thanks in advance.?
I'm not sure what's troubling you but in order to add multiple values inside, just put another nesting like what I've eluded in the comments section:
$map['pics'][] = $pic['pic'];
// ^
So to complete the answer:
$map = [];
$props = [];
foreach ($aTweets as $sTweet) {
$map['id'] = $sTweet['id'];
$map['tweet'] = $sTweet['tweet'];
$map['pics'] = []; // initialize
foreach ($pics as $pic) {
if ($pic['tweet_id'] === $sTweet['id']) {
$map['pics'][] = [$pic['pic']];
}
}
$props[] = $map;
}
This essentially creates another dimension for pics index as an array and continually pushing, provided they have the same ID.
Sidenote: tweet_id is to pics and id is to aTweets. Your's have the other way around.

Getting an object name within an object in PHP

In PHP, I have learned that to be able to get values from an object is to do something like this:
$objResult->{"RESP"}->{"DATA"}->{"F_NAME"}
However, for the data below, how will I be able to get the name "NO_1"?
Since its in an array, I want to be able to extract the data in it, and I'm thinking of getting the name of it first.
{
"SAMPLE": [
{
"NO_1": [
{
"RESULT": [
{
"NUMBER": 1,
"F_NAME": "JOHN",
"L_NAME": "SMITH"
},
{
"NUMBER": 2,
"F_NAME": "WILL",
"L_NAME": "JONES"
}
]
}
]
},
{
"NO_2": [
{
"RESULT": [
{
"NUMBER": 3,
"F_NAME": "MARY",
"L_NAME": "JANE"
},
{
"NUMBER": 4,
"F_NAME": "NEIL",
"L_NAME": "STRONG"
}
]
}
]
}
]
}
Any ideas?
There are two ways to get this. Either you can access direct index or iterate the loop to get all the members. Below is the example you can apply checks for error handling while accessing array indexes.
<?php
$json = '{
"SAMPLE": [
{
"NO_1": [
{
"RESULT": [
{
"NUMBER": 1,
"F_NAME": "JOHN",
"L_NAME": "SMITH"
},
{
"NUMBER": 2,
"F_NAME": "WILL",
"L_NAME": "JONES"
}
]
}
]
},
{
"NO_2": [
{
"RESULT": [
{
"NUMBER": 3,
"F_NAME": "MARY",
"L_NAME": "JANE"
},
{
"NUMBER": 4,
"F_NAME": "NEIL",
"L_NAME": "STRONG"
}
]
}
]
}
]
}';
$arr = json_decode($json,TRUE);
echo $arr['SAMPLE'][0]['NO_1'][0]['RESULT'][0]['F_NAME']; // Direct access
foreach ($arr as $key => $result){ // iterate in loop
foreach ($result as $key => $no) {
foreach ($no['NO_1'] as $key => $res) {
foreach ($res['RESULT'] as $key => $name) {
echo $name['F_NAME'];
}
}
}
}
die;
?>

PHP get json object name [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 6 years ago.
I have json array like that
{
"STATUS": "SUCCESS",
"MESSAGE": "",
"DATA": {
"list": [
{
"val0": {
"hidden": "0",
"rate": "10"
}
},
{
"val1": {
"hidden": "0",
"rate": "20"
}
}
],
"status": "Provisioned"
}
}
I want to get the object name of DATA>list>.
I tried with get_class($list[0]) but the output is stdClass. Output should be val0.How can I try. Please help
Use json_decode, list is also an array, Therefor first key(0) represent val0, and If you want to get inner content of the val0, then you have to loop it again.
$data = '{
"STATUS": "SUCCESS",
"MESSAGE": "",
"DATA": {
"list": [
{
"val0": {
"hidden": "0",
"rate": "10"
}
},
{
"val1": {
"hidden": "0",
"rate": "20"
}
}
],
"cpe_status": "Provisioned"
}
}';
$data = json_decode($data, true);
foreach($data['DATA']['list'][0] as $key=>$value){
echo $key; // return val0
echo "<br/>";
// to get val0 inner content
foreach($value as $item=>$list){
echo $item." - ".$list; // return val0 inner data
echo "<br/>";
}
}
// alternative way for loop val0 inner content
foreach($data['DATA']['list'][0]['val0'] as $key=>$value){
echo $key." - ".$value; // return val0 inner data
echo "<br/>";
}
Hopefully, the Self-Explanatory Snippet below could offer you a tip on how to go about doing it yourself. And by the way, you may Quick-Test it Here.
<?php
$strJson = '{
"STATUS" : "SUCCESS",
"MESSAGE" : "",
"DATA" : {
"list" : [
{
"val0" : {
"hidden" : "0",
"rate" : "10"
}
},
{
"val1" : {
"hidden" : "0",
"rate" : "20"
}
}
],
"cpe_status" : "Provisioned"
}
}';
$objJson = json_decode($strJson);
$data = $objJson->DATA;
$lists = $data->list;
$list0 = $lists[0];
$list1 = $lists[1];
var_dump($lists);
The var_dump($lists) above yields::
array (size=2)
0 =>
object(stdClass)[47]
public 'val0' =>
object(stdClass)[46]
public 'hidden' => string '0' (length=1)
public 'rate' => string '10' (length=2)
1 =>
object(stdClass)[49]
public 'val1' =>
object(stdClass)[48]
public 'hidden' => string '0' (length=1)
public 'rate' => string '20' (length=2)
Now, you can simply get all the data you want from the List using a simple loop like so:
<?php
foreach($lists as $objList){
if(is_object($objList)){
foreach($objList as $key=>$data){
// NOW, YOU CAN DO SOMETHING WITH THE DATA...
// LIKE GET THE `hidden` OR `rate` PROPERTIES/ATTRIBUTES
$hidden = $data->hidden;
$rate = $data->rate;
// var_dump($hidden);
// var_dump($rate);
// var_dump($key);
var_dump($data);
}
}
}
try
$data = '{
"STATUS": "SUCCESS",
"MESSAGE": "",
"DATA": {
"list": [
{
"val0": {
"hidden": "0",
"rate": "10"
}
},
{
"val1": {
"hidden": "0",
"rate": "20"
}
}
],
"status": "Provisioned"
}
}';
$data = json_decode($data);
$ss = $data->DATA->list;
echo $ss[0]->val0->rate;

Flatten a Multidimensional Array with key, value and object from a JSON

For 2 days, I'm trying to extract informations from a multidimensional array and I think I'm stuck after trying a lot of things
Here is my json
{
"profile": [
{
"id": "123456",
"hostId": null,
"description": [
{
"id": "name",
"value": "foo"
},
{
"id": "name2",
"value": "foo2"
},
{
"id": "bio",
"value": "heyyyy"
},
{
"id": "location",
"value": "somewhere"
}
],
"ishere": true
}
]
}
I want to manipulate it to have this
{
"id": "123456",
"host": null,
"name": "foo",
"name2": "foo2",
"bio": "heyyyy",
"location": "somewhere",
"ishere": true
}
with this (after a json_decode)
foreach ($array->profileUsers[0]->settings as $item) {
$out2[$item->id] = $item->value;
}
I only have
{
"name": "foo",
"name2": "foo2",
"bio": "heyyyy",
"location": "somewhere"
}
Thank you
This should do the trick:
$obj = json_decode($your_json);
$obj = $obj->profile[0];
foreach($obj->description as $d)
$obj->{$d->id} = $d->value;
unset($obj->description);
$data = json_decode($your_json, true);
$new_array = [];
foreach($data['profile'] as $key=>$item) {
if(is_array($item)) {
$new_array[$item['id']] = $item['value'];
}
else {
$new_array[$key] = $item;
}
}
Hardcoded this, hope it will help.

How to choose first key of foreach() within a foreach()

I cant seem to get this working right it just returns each of value0. I only want the first key under data1 so the values of 1111 and 3333. If I add a key to value0 I get "1" as its value and the same number of them are displayed. In this example there are four and only two should return.
Json:
{
"json": "success",
"data": [
{
"data0": "123",
"data1": [
{
"value0": "1111",
"value1": "aaaa"
},
{
"value0": "2222",
"value1": "bbbb"
}
]
},
{
"data0": "abc",
"data1": [
{
"value0": "3333",
"value1": "cccc"
},
{
"value0": "4444",
"value1": "dddd"
}
]
}
],
"number": 300,
"end": ""
}
PHP:
foreach( $json->data as $data) {
foreach($data->data1 as $value) {
echo "{$value->value0}<br>";
}
}
if you want both array 0 index
$json = json_decode($json, true);
foreach( $json['data'] as $data) {
echo $data['data1'][0]['value0']; //11113333
}
or use directly without foreach for get one value
echo $json['data'][0]['data1'][0]['value0']; //1111
To keep your object version, you could loop like so:
$jsonObj = json_decode($json);
foreach($jsonObj as $value) {
foreach($value as $data => $object) {
echo $object->data1[0]->value0;
}
}
Should give you:
11113333

Categories