Decode json and count array equal - php

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
)

Related

PHP flatten a Multidimensional Array with keys

I wrote some PHP code to line up the children of an array. I wrote a recursive function.
Everything is listed correctly one below the other, but some arrays do not have the "Name" key.
Does anyone have any idea how I can get it to show everyone's "Name" key?
My PHP Code:
$json = '[
{
"name": "A",
"children": [
{
"name": "B",
"children": [
{
"name": "C"
},
{
"name": "D",
"children": [
{
"name": "E"
},
{
"name": "F"
}
]
}
]
},
{
"name": "G"
}
]
},
{
"name": "H"
}
]';
header('Content-Type: application/json; charset=utf-8');
$json = json_decode($json, true);
function array_flatten($array, $prefix = '') {
$return = array();
foreach ($array as $key => $value) {
if (is_array($value) && array_key_exists("children", $value)){
$return = array_merge($return, array_flatten($value, $key));
}else if (is_array($value) && count($value) > 1){
foreach ($value as $keyA => $valueA) {
if (is_array($valueA) && array_key_exists("children", $valueA)){
$return = array_merge($return, array_flatten($valueA, $keyA));
}else{
$return[] = $valueA;
}
}
} else {
$return[] = $value;
}
}
return $return;
}
echo json_encode(array_flatten($json));
Current Result:
["A","B",{"name":"C"},"D",{"name":"E"},{"name":"F"},{"name":"G"},{"name":"H"}]
What I want:
[{"name":"A"},{"name":"B"},{"name":"C"},{"name":"D"},{"name":"E"},{"name":"F"},{"name":"G"},{"name":"H"}]
Here is a working code :
<?php
$json = '[
{
"name": "A",
"children": [
{
"name": "B",
"children": [
{
"name": "C"
},
{
"name": "D",
"children": [
{
"name": "E"
},
{
"name": "F"
}
]
}
]
},
{
"name": "G"
}
]
},
{
"name": "H"
}
]';
$json = json_decode($json, true);
function getArrayValuesRecursively(array $array){
$values = [];
foreach ($array as $value) {
if (is_array($value)) {
$values = array_merge(
$values,
getArrayValuesRecursively($value)
);
} else {
$values[] = ['name' => $value];
}
}
return $values;
}
echo json_encode(getArrayValuesRecursively($json));
Demo : https://3v4l.org/01Fla
Function getArrayValuesRecursively(array $array) is from Get all values from multidimensional array
here's my take on it:
$json = json_decode($json, true);
$names = get_names_of_people($json);
print(json_encode($names));
function get_names_of_people(array $people): array
{
$names = [];
foreach ($people as $person) {
foreach ($person as $key => $value) {
switch ($key) {
case 'name':
$names[] = [
'name' => $value,
];
break;
case 'children':
$names = array_merge($names, get_names_of_people($value));
}
}
}
return $names;
}
$array = json_decode($json, true);
$result = [];
array_walk_recursive($array, function ($value, $key) use(&$result) {
$result[][$key] = $value;
});

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.

PHP foreach + continue not working on multidimensional array

I'm looking for a way to filter the array on a foreach loop based on two parameters..
I have in my output the following array:
[
{
"entry_id": "1",
"title": "something",
"grades": [
"3",
"4",
"5",
"6"
],
"subject": [
"science"
]
},
{
"entry_id": "2",
"title": "something else",
"grades": [
"7",
"8",
"9",
"10"
],
"subject": [
"math"
]
},
]
I'm trying to return only entry_id 2 using foreach + break, from what I've read it seems like this should work..
$subject = 'math';
$grade = '10';
foreach ( $results as $key => &$result ) {
if($subject && !in_array($subject, $result['subject'])){
break;
}
if($grade && !in_array($grade, $result['grades'])){
break;
}
}
But it's returning all entries..
After searching some more seems like unset + array_values will do what I need:
foreach ( $results as $key => &$result ) {
if($subject && !in_array($subject, $result['subject'])){
unset($results[$key]);
$results = array_values($results);
}
if($grade && !in_array($grade, $result['grades'])){
unset($results[$key]);
$results = array_values($results);
}
}
It seems like you need to add the current entry to a new array when it passes any of the tests. So change the !in_array() test to in_array(), and add to the result inside that if block.
$realresults = array();
foreach ( $results as $key => &$result ) {
if($subject && in_array($subject, $result['subject'])){
$realresults[] = $result;
} elseif($grade && in_array($grade, $result['grades'])){
$realresults[] = $result;
}
}

Using foreach in PHP with JSON

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

Categories