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;
});
Related
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.
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.
How can in php get the value name out of this object and out of this array of objects? And how can check is object or array object and then get value name?
"director": {
"#type": "Person",
"url": "/name/nm0001104/",
"name": "Frank Darabont"}
"director": [
{
"#type": "Person",
"url": "/name/nm5156926/",
"name": "Devon Downs"
},
{
"#type": "Person",
"url": "/name/nm2632302/",
"name": "Kenny Gage"
}],
$json = '{
"director": [
{
"#type": "Person",
"url": "/name/nm5156926/",
"name": "Devon Downs"
},
{
"#type": "Person",
"url": "/name/nm2632302/",
"name": "Kenny Gage"
}
]
}';
$names = [];
$data = json_decode($json, true);
if (true === isset($data['name'])) {
$name[] = $data['name'];
return $names;
}
foreach ($data as $director) {
foreach($director as $itme){
if (true === isset($itme['name'])) {
$names[] = $itme['name'];
}
}
}
return $names;
Output :
Array
(
[0] => Devon Downs
[1] => Kenny Gage
)
use json_decode.
$names = [];
$data = json_decode($json, true);
if (true === isset($data['name'])) {
$name[] = $data['name'];
return $names;
}
foreach ($data as $director) {
if (true === isset($director['name'])) {
$names[] = $director['name'];
}
}
return $names;
I need to count the field which starts with the same prefix value in PHP laravel before submitting.
Below is the Laravel response and here I need to count the field name which starts with "of_".
{
"_token": "c3wPhNtM86QujtsugZaZTonLUnWJBWjyyRMhorsd",
"name": null,
"type": null,
"no_of_guest": "200",
"time": "Breakfast",
"price": null,
"service_charge": null,
"of_1": [
"1",
"6"
],
"of_2": [
"8",
"11"
],
"of_3": [
"2",
"12"
]
}
Something like this should help you.
<?php
$json = '{"_token":"c3wPhNtM86QujtsugZaZTonLUnWJBWjyyRMhorsd","name":null,"type":null,"no_of_guest":"200","time":"Breakfast","price":null,"service_charge":null,"of_1":["1","6"],"of_2":["8","11"],"of_3":["2","12"]}';
$decoded = json_decode($json);
foreach ($decoded as $key => $value) {
if (strpos($key, 'of_') === 0) {
echo print_r($value);
}
}
If you want to count how many fields in the JSON starts with of_ you can use starts_with helper
$json = '{"_token":"c3wPhNtM86QujtsugZaZTonLUnWJBWjyyRMhorsd","name":null,"type":null,"no_of_guest":"200","time":"Breakfast","price":null,"service_charge":null,"of_1":["1","6"],"of_2":["8","11"],"of_3":["2","12"]}';
$array = json_decode($json, true);
$count = 0;
foreach ($array as $key => $value) {
if (starts_with($key, 'of_')) $count++;
}
return $count;
Output
3
And if you want to calculate the sum of each 2 values in each of_ key
$json = '{"_token":"c3wPhNtM86QujtsugZaZTonLUnWJBWjyyRMhorsd","name":null,"type":null,"no_of_guest":"200","time":"Breakfast","price":null,"service_charge":null,"of_1":["1","6"],"of_2":["8","11"],"of_3":["2","12"]}';
$array = json_decode($json, true);
foreach ($array as $key => &$value) {
if (starts_with($key, 'of_')) {
$value = (int) $value[0] + (int) $value[1];
}
}
return $array;
Output
{
"_token": "c3wPhNtM86QujtsugZaZTonLUnWJBWjyyRMhorsd",
"name": null,
"type": null,
"no_of_guest": "200",
"time": "Breakfast",
"price": null,
"service_charge": null,
"of_1": 7,
"of_2": 19,
"of_3": 14
}
And if you want to sum all values
$json = '{"_token":"c3wPhNtM86QujtsugZaZTonLUnWJBWjyyRMhorsd","name":null,"type":null,"no_of_guest":"200","time":"Breakfast","price":null,"service_charge":null,"of_1":["1","6"],"of_2":["8","11"],"of_3":["2","12"]}';
$array = json_decode($json, true);
$sum = 0;
foreach ($array as $key => &$value) {
if (starts_with($key, 'of_')) {
$sum += (int) $value[0] + (int) $value[1];
}
}
return $sum;
Output
40
Hope this helps
I'm not able to get this code working:
$paths = ['2014/','2014/04/','2015/'];
$tree = array();
foreach ($paths as $path) {
$dir_exploded = explode("/", $path);
array_pop($dir_exploded);
$tmp = array();
for ($i = count($dir_exploded) - 1; $i >= 0; $i--) {
if ($i == count($dir_exploded) - 1) {
$children = array();
} else {
$children = array($tmp);
}
$tmp = array('text' => $dir_exploded[$i], 'children' => $children);
}
$tree = array_replace_recursive($tree, $tmp);
}
echo(json_encode(array(array('text' => '/', 'children' => array($tree)))));
I get:
[
{
"text": "/",
"children": [
{
"text": "2015",
"children": [
{
"text": "04",
"children": []
}
]
}
]
}
]
So 2014 have been delete by the merge of this 2 arrays. I would like to get:
[
{
"text": "/",
"children": [
{
"text": "2014",
"children": [
{
"text": "04",
"children": []
}
]
},{
"text": "2015",
"children": []
}
]
}
]
At least I want to send this tree by json using json_encode, or a better way if you know one.
Try this code, I have change little code of yours and add some extra paths.
$paths = array('2014/', '2014/04/','2014/03/','2015/');
$new_tree = $temp_new_tree = array();
foreach ($paths as $path)
{
$dir_exploded = explode("/", $path);
array_pop($dir_exploded);
$temp_new_tree = (!empty($new_tree)) ? $new_tree : array();
$tmp = $tree = array();
for ($i = count($dir_exploded) - 1; $i >= 0; $i--)
{
if ($i == count($dir_exploded) - 1) {
$children = array();
} else {
$children = array($tmp);
}
$tmp = array('text' => $dir_exploded[$i], 'children' => $children);
}
$tree = array_replace_recursive($tree, $tmp);
$new_tree[$dir_exploded[0]] = $tree;
if(array_key_exists($dir_exploded[0], $temp_new_tree))
{
$new_tree[$dir_exploded[0]]['children'] = array_merge($new_tree[$dir_exploded[0]]['children'], $temp_new_tree[$dir_exploded[0]]['children']);
}
}
//echo json_encode(array(array('text' => '/', 'children' => array($new_tree))));
$new_tree = array_shift(array_chunk($new_tree, count($new_tree)));
echo json_encode(array(array('text' => '/', 'children' => $new_tree)));
Output will be like this:--
[
{
text: "/",
children: [
{
text: "2014",
children: [
{
text: "03",
children: [ ]
},
{
text: "04",
children: [ ]
}
]
},
{
text: "2015",
children: [ ]
}
]
}
]
Hope this will help you...
You can use following;
<?php
$paths = array('2014/01/02','2014/04/03','2015/07');
$all = array();
foreach ($paths as $path) {
$temp = explode("/", $path);
$all[] = tree($temp, 0);
}
var_dump($all);
function tree($arr, $i) {
if (count($arr) == ($i + 1)) return $arr[$i];
return array(
"text" => $arr[$i],
"children" => tree($arr, $i+1)
);
}
Here is a working demo: codepad