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
Related
Here is my JSON
[
{
"TIMESTAMP": "2021-06-09 13:13:26",
"COL1": "10",
"COL2": "20",
"COL3": "30"
},
{
"TIMESTAMP": "2021-06-22 13:13:26",
"COL1": "20",
"COL2": "30",
"COL3": "40"
},
{
"TIMESTAMP": "2021-06-21 13:13:26",
"COL1": "1",
"COL2": "2",
"COL3": "3"
},
{
"TIMESTAMP": "2021-06-20 13:13:26",
"COL1": "40",
"COL2": "50",
"COL3": "60"
}
]
I need to refactor the json According to the Column name like (EXPECTED OUTPUT)
[
{
"TITLE":"COL1"
"DATA":[10,20,1,40]
},
{
"TITLE":"COL2"
"DATA":[20,30,2,50]
},
{
"TITLE":"COL3"
"DATA":[30,40,3,60]
},
]
I was tried but it not working
$data = json_decode($result, true);
$refactored = array_map(function($item) {
return (object)[
'TIMESTAMP' => $item['TIMESTAMP'],
'DATA' => [ $item['COL1'], $item['COL2'], $item['COL3'] ]
];
}, $data);
dump($refactored);
Someone help me out with this. The column may be 3 or more and it must be dynamic. Thanks in advance.
You can transform your JSON like this:
$data = json_decode($result, true);
$refactored = array_reduce($json, function($carry, $item) {
foreach($item as $key => $value) {
if (str_starts_with($key, 'COL')) {
$index = substr($key, 3, 1) - 1;
if (!isset($carry[$index])) {
$carry[$index] = [
'Title' => $key
];
}
$carry[$index]['Data'][] = $value;
}
}
return $carry;
}, []);
dump($refactored);
I am always a fan of using the value you want to group your data by as a temporary array key, that makes things easier, and can simply be reset by using array_values afterwards.
$input = json_decode('…', true);
$output = [];
foreach($input as $item) {
foreach($item as $key => $value) {
if($key != 'TIMESTAMP') {
$output[$key]['TITLE'] = $key;
$output[$key]['DATA'][] = (int)$value;
}
}
}
$output = array_values($output);
echo json_encode($output);
All you have to do is re-encode the processed data:
json_encode($refactored) will give you the output that you want.
P.S. you don't have to cast to an object. It works as array as well.
Please can any help me on this, to remove all keys that have values of N/A, -, or empty strings. If one of the values appear in an array then remove that single item from the array
{
"name": {
"first": "Robert",
"middle": "",
"last": "Smith"
},
"age": 25,
"DOB": "-",
"hobbies": [
"running",
"coding",
"-"
],
"education": {
"highschool": "N/A",
"college": "Yale"
}
}
Expecting result would be:
{
"name": {
"first": "Robert",
"last": "Smith"
},
"age": 25,
"hobbies": [
"running",
"coding"
],
"education": {
"highschool": "N/A",
"college": "Yale"
}
}
You could use following logic to remove elements from your source data:
The recursive function cleanUp() cycles through the data and removes all the entries with values that are set in array $remove
$arr = json_decode($json, true);
$remove = ['N/A', '-','',];
cleanUp($arr, $remove);
function cleanUp(array &$arr, array $remove = [])
{
foreach($arr as $key => &$value) {
if(is_array($value)) {
cleanUp($value, $remove);
} else {
if(in_array($value, $remove)) unset($arr[$key]);
}
}
}
working demo
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;
?>
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);
How to group array by 'tax'and 'concept' and SUM attribute 'val'?
I looking for create a single object when tax and concept are the same, also SUM the val.
I tried with simple foreach and validation inside, but doesnt work.
thanks.
echo json_encode($array);
Array Print
[
{
"tax": "10",
"concept": "TUC",
"val": "10"
},
{
"tax": "10",
"concept": "TUC",
"val": "86"
},
{
"tax": "15",
"concept": "TUC",
"val": "8"
},
{
"tax": "11",
"concept": "IPS",
"val": "6"
},
{
"tax": "11",
"concept": "IPS",
"val": "45"
}
]
Expected Result
[
{
"tax": "10",
"concept": "TUC",
"val": "96"
},
{
"tax": "15",
"concept": "TUC",
"val": "8"
},
{
"tax": "11",
"concept": "IPS",
"val": "51"
}
]
You can use array_reduce() here. You'll use the tax value as a key you're grouping on, and reduce the array to unique tax elements while simultaneously producing the sum of val values. The only caveat with this approach is that transforming it to JSON will make PHP think that the outer element is an object and not an array (even though it is an array, this is because we end up using non-default array indexing). But, this is easily mitigated with a call to array_values().
$array = // your array from above
$result = array_reduce($array, function($carry, $item) {
if(!isset($carry[$item->tax])) {
$carry[$item->tax] = $item;
} else {
$carry[$item->tax]->val += $item->val;
}
return $carry;
});
$result = array_values($result);
echo json_encode($result);
You can see from this demo that it produces:
[{
"tax": "10",
"concept": "TUC",
"val": 96
}, {
"tax": "15",
"concept": "TUC",
"val": "8"
}, {
"tax": "11",
"concept": "IPS",
"val": 51
}]
$array // Your array
$result = [];
array_walk($array, function($object) use (&$result) {
$notExist = true;
foreach ($result as $item) {
if ($item->tax == $object->tax && $item->concept == $object->concept) {
$item->val += $object->val;
$notExist = false;
break;
}
}
if ($notExist) {
array_push($result, $object);
}
});
echo json_encode($result);
First group the objects:
$groups = [];
foreach($array as $object){
$groups[$object->tax . "\0" . $object->concept] = $object;
// I use the NUL byte to delimit, assuming it is absent in $tax and $concept
}
Then map each group into a summed-up object.
$output = array_map(function(array $group){
$object = new stdClass;
$object->tax = $group[0]->tax;
$object->concept = $group[0]->concept;
$object->val = array_reduce($group, function($carry, $item){
return $carry + $item->val;
}, 0);
return $object;
}, $groups);
<?php
$arr_str = '[
{"tax":"10", "concept":"TUC", "val":"10"},
{"tax":"10", "concept":"TUC", "val":"86"},
{"tax":"15", "concept":"TUC", "val":"8"},
{"tax":"11", "concept":"IPS", "val":"6"},
{"tax":"11", "concept":"IPS", "val":"45"}
]';
$arr = json_decode($arr_str);
$tmp_array = [];
foreach ($arr as $e) {
// combine "tax" and "concept" so we can use both of them as key. Use "_" as delimiter.
$key = $e->tax . "_" . $e->concept;
// sum the "val" if the key exists, otherwise assign it
isset($tmp_array[$key]) ? $tmp_array[$key] += $e->val : $tmp_array[$key] = $e->val;
}
$grouped_array = [];
foreach ($tmp_array as $k => $v) {
// ungroup the key so we can create an array like the original one
$tmp = explode("_", $k);
$grouped_array[] = (object)["tax" => $tmp[0], "concept" => $tmp[1], "val" => $v];
}
echo json_encode($grouped_array);
?>