Using foreach in PHP with JSON - php

I have a JSON file like this:
[
{
"set_id": "10001",
"name": "4x4 car",
"img_url": "https://xxx.xxx.com/img/sets-b/10001.jpg",
"parts": [
{
"part_id": "1001",
"qty": "2",
"color_id": "0",
"type": 1
},
{
"part_id": "1002",
"qty": "2",
"color_id": "0",
"type": 1
},
{
"part_id": "1003",
"qty": "2",
"color_id": "0",
"type": 1
},
{
"part_id": "1004",
"qty": "2",
"color_id": "0",
"type": 1
}
]
}
]
I am using PHP code like this:
while($item = array_shift($json_output))
{
foreach ($item as $key => $value)
{
echo $key.' => '.$value."\n";
}
}
But it returns the result:
set_id => 9398-1 descr => 4 x 4 Crawler set_img_url => https://img.rebrickable.com/img/sets-b/9398-1.jpg parts => Array
How do I want to return the parts info?

If you want only the parts
foreach ($item{"parts"] as $key => $value)
{
echo $key.' => '.$value."\n";
}
Sample here: http://sandbox.onlinephpfunctions.com
If you want every 2 level property:
$items=json_decode($json,true);
foreach ($items as $item) {
foreach ($item as $key => $value)
{
if( is_array($value) ) {
foreach ($value as $subkey => $part)
{
foreach ($part as $partkey => $partvalue)
{
echo $key .' '. $subkey . ' ['.$partkey.'] => '.$partvalue."\n";
}
}
} else {
echo $key.' => '.$value."\n";
}
}
}

Maybe you can use $array_json = json_decode($json_var, true) and then $parts = $array_json["parts"]; (I haven't execute the code, maybe has some errors)
http://php.net/manual/en/function.json-decode.php

Related

merge object in php

i have below json data
{
"data": [
{
"minggu a": "2",
"total a": "377033"
},
{
"minggu b": "1",
"total b": "136615"
}
]
and this is the code i made in controller
$satu= $this->model->db_week_resTender();
$arr = [];
foreach($satu as $val){
$arr['data'][] = array(
'minggu' => $val['minggu'],
'total' => $val['total']
);
}
$response = $this->set_response($arr,200);
}
how to concatenate below json data
here I issue data with a limit of 2.
{
"data": [
{
"minggu a": "2",
"total a": "377033"
"minggu b": "1",
"total b": "136615"
},
]
}
$data = '{
"data": [
{
"minggu a": "2",
"total a": "377033"
},{
"minggu b": "1",
"total b": "136615"
}
]
}';
$decoded_satu=json_decode($data,true);
$arr = [];
foreach($decoded_satu['data'] as $key=> $val){
foreach ($val as $subkey => $subvalue) {
$arr['data'][$subkey] = $subvalue;
}
}
$finalArray = json_encode($arr);
echo "<pre>";print_r($finalArray) ;die;
foreach($statu as $index => $val){
$arr['data'][$index] = $val;
}
This should give the result you have posted at the end.

Convert JSON IN LARAVEL

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.

Acessing specific key/values in nested array in each iteration

I am only interested in keys class and score and their values in my nested array. How can I only get these keys values to be printed out?
This is my $result array.
{ "images": [ { "classifiers": [ { "classifier_id": "default", "name": "default", "classes": [ { "class": "banana", "score": 0.562, "type_hierarchy": "/fruit/banana" }, { "class": "fruit", "score": 0.788 }, { "class": "diet (food)", "score": 0.528, "type_hierarchy": "/food/diet (food)" }, { "class": "food", "score": 0.528 }, { "class": "honeydew", "score": 0.5, "type_hierarchy": "/fruit/melon/honeydew" }, { "class": "melon", "score": 0.501 }, { "class": "olive color", "score": 0.973 }, { "class": "lemon yellow color", "score": 0.789 } ] } ], "image": "fruitbowl.jpg" } ], "images_processed": 1, "custom_classes": 0}
And this is my code logic.
foreach($result as $imgage => $classifier)
{
foreach($classifier["classes"] as $clas)
{
foreach($clas as $key => $value)
{
echo $key . ": " . $value;
}
}
}
This should work for you,
<?php
$string = '{"images":[{"classifiers":[{"classifier_id":"default","name":"default","classes":[{"class":"banana","score":0.562,"type_hierarchy":"/fruit/banana"},{"class":"fruit","score":0.788},{"class":"diet (food)","score":0.528,"type_hierarchy":"/food/diet (food)"},{"class":"food","score":0.528},{"class":"honeydew","score":0.5,"type_hierarchy":"/fruit/melon/honeydew"},{"class":"melon","score":0.501},{"class":"olive color","score":0.973},{"class":"lemon yellow color","score":0.789}]}],"image":"fruitbowl.jpg"}],"images_processed":1,"custom_classes":0}';
$array = json_decode($string,1);
foreach($array['images'] as $key => $images)
{
foreach($images['classifiers'] as $key => $classes)
{
foreach($classes['classes'] as $cls_score){
echo "class = ". $cls_score['class']. " & score = ". $cls_score['score'].PHP_EOL;
}
}
}
WORKING DEMO: https://3v4l.org/vF2RL
Can you try ?
$str = '{ "images": .... }';
// get associative array from json
$result = json_decode($str, true)['images'];
foreach ($result as $imgage => $classifiers) {
foreach ($classifiers["classifiers"] as $classifier) {
foreach ($classifier["classes"] as $clas) {
foreach ($clas as $key => $value) {
// you can add condition here to target only desired keys
echo $key . ": " . $value;
}
}
}
}

get multidimension array key value to single array php

{
"list": [
{
"id": 62,
"user_id": "34",
"updated_at": "2017-10-15 08:24:32",
"request": {
"data": "yes",
"watch": "Pending"
}
},
{
"id": 63,
"user_id": "34",
"updated_at": "2017-10-15 08:24:32",
"request": {
"data": "yes",
"watch": "Yes"
}
}, ]
}
How can i get the watch value to under the updated_at
As Expected
"list": [
{
"id": 62,
"user_id": "34",
"updated_at": "2017-10-15 08:24:32",
"watch": "Pending"
}..
I tried using array_column but doesn't work for me.
function array_column($array, $column){
$ret = array();
foreach($array as $row){
$ret[] = $row[$column];
return $ret;
}
}
Somewhat like
function updateArray(&$array){
foreach($array['list'] as $key => $item){
$array['list'][$key]['watch'] = $item['request']['watch'];
unset($array['list'][$key]['request']);
}
}
updateArray($array);
print_r($array);
Demo
I assume that you know that you need to decode the JSON first:
$array = json_decode($json, true);
Then access the array under the list element:
$result = array_column($array['list'], 'updated_at');
It was a good challenge.here you are
<pre>
<?php
$array=array("list"=>array(array("id"=>"62","user_id"=>"32","updated_at"=>2017,"request"=>array("data"=>"yes","watch"=>"panddin")),
array("id"=>"60","user_id"=>"30","updated_at"=>2016,"request"=>array("data"=>"no","watch"=>"pan"))));
//print_r($array);
foreach($array as $row){
foreach ($row as $key => $value){
if((is_array($value))){
foreach ($value as $key1 => $k){
if((is_array($k))){
foreach ($k as $key2 => $value2) {
echo $key2."=>". $value2."<br>";
}
}else echo $key1."=>".$k."<br>";
}
}else echo $key."=>".$value. "<br>";
}
}
?>
</pre>

Decode json and count array equal

I need to count how many arrays are equal after a decode json.
{
"IP": [
{
"C_P": "US",
"C_L": "United States"
},
{
"C_P": "IT",
"C_L": "ITALY"
},
{
"C_P": "US",
"C_L": "United States"
},
{
"C_P": "CO",
"C_L": "Colombia"
},
{
"C_P": "US",
"C_L": "United States"
}
]
}
Using a process loop that counts the array "C_P", the result should be:
3: US
1: IT
1: CO
Thanks.
$result = json_decode($json);
$countArray = array();
foreach ($result as $key => $element) {
foreach ($element as $cp)
if (isset($countArray[$cp->C_P]))
$countArray[$cp->C_P] ++;
else
$countArray[$cp->C_P] = 1;
}
Try something like below
$array = (array)json_decode($a, true);
$index = array();
foreach ($array['IP'] as $key => $value){
unset($value['C_L']);
foreach ($value as $key2 => $value2){
if (array_key_exists($value2, $index)){
$index[$value2]++;
} else {
$index[$value2] = 1;
}
}
}
print_r($index);
Output:
Array
(
[US] => 3
[IT] => 1
[CO] => 1
)

Categories