I want to add values from one array to another that are both potentially multidimensional when they have the same ID. Hard to explain so I added example.
arr1 => new structure, without full data
arr2 => old structure, with full data
Examples if you'd like to help out:
// arr1 (the correct structure/order, without the full data)
[{
"id": "24",
"children": [{
"id": "21",
"children": [{
"id": "15"
}]
}]
}]
// arr2 (full data, not in any specific order, may be nested)
[{
"id": "24",
"name": " x",
"time": "0",
"status": "0"
}, {
"id": "21",
"children": [{
"id": "15",
"name": "x",
"time": "0",
"status": "0"
}],
"name": "x",
"time": "0",
"status": "0"
}]
// arr3 (desired output for this example)
[{
"id": "24",
"children": [{
"id": "21",
"children": [{
"id": "15",
"name": "x",
"time": "0",
"status": "0"
}],
"name": "x",
"time": "0",
"status": "0"
}],
"name": " x",
"time": "0",
"status": "0"
}]
I tried this:
function merge($arr1, $arr2) {
foreach($arr1 as $key => $value){
foreach($arr2 as $value2) {
if($value['id'] === $value2['id']){
$arr1[$key]['name'] = $value2['name'];
$arr1[$key]['time'] = $value2['time'];
$arr1[$key]['status'] = $value2['status'];
if (is_array($value)) {
$arr1[$key]['children'] = merge($arr1, $arr2);
}
}
}
}
return $arr1;
}
to combine them, but I can't figure out how to handle the nesting correctly. I have tried a lot of other things as well like using array_merge_recursive() but it doesn't work because I want to merge based on ID value. Any help on getting me on track would be awesome thanks.
Current output for example:
[{
"id": "24",
"children": [{
"id": "21",
"children": [{
"id": "15"
}]
}],
"name": " x",
"time": "0",
"status": "0"
}]
Desired output for example:
[{
"id": "24",
"children": [{
"id": "21",
"children": [{
"id": "15",
"name": "x",
"time": "0",
"status": "0"
}],
"name": "x",
"time": "0",
"status": "0"
}],
"name": " x",
"time": "0",
"status": "0"
}]
Edit: How about this?
$detailsClean = [];
foreach($array2 as $item) {
$detailsClean = removeDepth($item, $detailsClean);
}
foreach($array1 as $itemKey => $item) {
$array1[$itemKey] = addDetails($item, $detailsClean);
}
function removeDepth($array, $result) {
$id = $array['id'];
if (!empty($array['children'])) {
foreach($array['children'] as $child) {
$result = removeDepth($child, $result);
}
unset($array['children']);
}
$result[$id] = $array;
return $result;
}
function addDetails($array, $details) {
$id = $array['id'];
if (isset($details[$id])) {
$array = array_merge($array, $details[$id]);
if (!empty($array['children'])) {
foreach($array['children'] as $childKey => $child) {
$array['children'][$childKey] = addDetails($child, $details);
}
}
}
return $array;
}
$array1 is updated with the final result.
Here is an example with the data from your unedited post: http://phpio.net/s/7z09
EDIT - I think I understand the problem now
From the example you gave, I realised the problem - your old array has all the data, but not the parent-child relationships, so you want to populate the new array (with the correct relationships) with the data form the old array. The problem here is that the merge function would have to fetch data from an arbitrary generation in the old array to populate the new array. This could mean a lot of looping.
So I think the solution is first to loop through the old data and flatten it - just have an associative array where the key is the "id" value. Then go through the new array and populate it from the flattened, "lookup" array. Does that make sense? In any case, you'd have two functions:
$lookUp = array();
//recursive function to flatten $arr2 into $lookUp array.
function indexOriginal($arr, &$lookUp) {
foreach($arr as $value) {
$lookUp[$value["id"]] = $value;
if (isset($value['children'])) {
unset($lookUp[$value["id"]]['children']);
indexOriginal($value['children'], $lookUp);
}
}
}
indexOriginal($arr2, $lookUp);
Then you populate the new array:
function fillInNew($arr, $lookUp) {
$return = array();
foreach($arr as $value) {
$newEntry = $lookUp[$value["id"]];
if (isset($value['children'])) $newEntry['children'] = fillInNew($value['children'], $lookUp);
$return[] = $newEntry;
}
return $return;
}
$newArr = fillInNew($arr1, $lookUp);
And $newArr should be what you're looking for
OLD USELESS STUFF FROM BEFORE:
This part of your code is weird to me:
if (is_array($value)) {
$arr1[$key]['children'] = merge($arr1, $arr2);
}
Obviously I may be completely confused, but don't you just need to put this?
if (isset($value2['children'])) $arr1[$key]['children'] = array_merge($arr1[$key]['children'], $value2['children']);
EDIT: I added array_merge because I saw that the 'children' array in the incomplete version could also need merging.
EDIT 2: now I've noticed that children can have further children (makes sense, I guess), which is why you had the correct idea of using the function recursively. You just seem to have passed in the wrong arrays - you want to pass in $arr1[$key]['children'] (as the incomplete array) and $value2['children'] (as the complete array)
function merge($arr1, $arr2) {
foreach($arr1 as $key => $value){
foreach($arr2 as $value2) {
if($value['id'] === $value2['id']){
$arr1[$key]['name'] = $value2['name'];
$arr1[$key]['time'] = $value2['time'];
$arr1[$key]['status'] = $value2['status'];
if (isset($value2['children'])) $arr1[$key]['children'] = merge($arr1[$key]['children'], $value2['children']);
}
}
}
return $arr1;
}
Related
I tried to parse a JSON using PHP from url. I need a list of item that have no children - means children field should be empty array and parent_id shouldn't be 0 - means not be parents.
JSON:
{
"body": {
"data": [
{
"id": 1,
"name": "car",
"parent_id": "0",
"children": [
{
"id": 2,
"name": "bmw",
"parent_id": "1",
"children": [
{
"id": 4,
"name": "bmw i8",
"parent_id": "2",
"children": []
}
]
},
{
"id": 3,
"name": "mustang",
"parent_id": "1",
"children": []
}
]
},
{
"id": 5,
"name": "clothes",
"parent_id": "0",
"children": []
},
{
"id": 6,
"name": "mobile",
"parent_id": "0",
"children": [
{
"id": 7,
"name": "apple",
"parent_id": "6",
"children": [
{
"id": 9,
"name": "Iphone 12 pro",
"parent_id": "7",
"children": []
},
{
"id": 10,
"name": "Iphone 11",
"parent_id": "7",
"children": []
}
]
},
{
"id": 8,
"name": "Xiaomi",
"parent_id": "6",
"children": []
}
]
}
]
}
}
Output Expected:
[4,3,9,10,8]
This is my php code that i tried and doesn't work.
$CategoryUrl = file_get_contents(self::CATEGORY_URL,true);
$array = json_decode($CategoryUrl,true);
$list = array();
foreach( $array['body']['data'] as $value ){
if (($value['parent_id'] != 0) && empty($value['children'])) {
foreach( $value['children'] as $val ){
$list[] = $val;
}
}
}
print_r($list);
It is indeed a little tricky to keep track of parent ID values and children call using array_walk_recursive as it jumps directly to its children. However, this can be still accomplished with your own recursive version like below. Keep checking with parent_id and children count. If both constraints satisfy, add them to $result, else keep calling children recursively.
<?php
$str = '{"body":{"data":[{"id":1,"name":"car","parent_id":"0","children":[{"id":2,"name":"bmw","parent_id":"1","children":[{"id":4,"name":"bmw i8","parent_id":"2","children":[]}]},{"id":3,"name":"mustang","parent_id":"1","children":[]}]},{"id":5,"name":"clothes","parent_id":"0","children":[]},{"id":6,"name":"mobile","parent_id":"0","children":[{"id":7,"name":"apple","parent_id":"6","children":[{"id":9,"name":"Iphone 12 pro","parent_id":"7","children":[]},{"id":10,"name":"Iphone 11","parent_id":"7","children":[]}]},{"id":8,"name":"Xiaomi","parent_id":"6","children":[]}]}]}}';
$data = json_decode($str,true);
$result = [];
function walkRecursive($data,&$result){
foreach($data as $entry){
if($entry['parent_id'] != 0 && count($entry['children']) == 0){
$result[] = $entry['id'];
}else{
walkRecursive($entry['children'],$result);
}
}
}
walkRecursive($data['body']['data'],$result);
print_r($result);
We can solve this problem by function call recursive algorithm,
hope it clear for you
$CategoryUrl = file_get_contents(self::CATEGORY_URL,true);
$array = json_decode($CategoryUrl, true);
$items = $array['body']['data'];
$list = [];
findParentIds(items, $list);
// doSomething
print_r($list);
/**
* passe by ref (list)
* #param array $children
* #param $list
*/
function findParentIds(array $children, & $list)
{
foreach ($children as $child) {
// use case 1: has no children and parent_id is 0 , just continue
if (empty($child['children']) && $child['parent_id'] == "0") {
continue;
}
// use case 2: has no children and parent_id is 0 , it's parent item
if (empty($child['children']) && $child['parent_id'] != "0") {
array_push($list, $child['id']);
}
// has children and parent_id is not 0 , recall function to treat use case 1 and 2 ..
findParentIds($child['children'], $list);
}
}
I have an array, which i wrote like a table for more reability.
[{
"id": "1",
"title": "boune",
"value": "3"
}, {
"id": "2",
"title": "check",
"value": "4"
}, {
"id": "3",
"title": "boune",
"value": "5"
}]
As the result of what i want to see is this json, where 'value' of identical 'titles' united inside [] brackets. I am very newbie in php. I undestand that i need for loop to sort query result, but can`t heck...Cant even put my mind to it...
[{
"id":"1",
"title": "boune",
"value": [3, 5]
}]
<?php
$json = '[{"id":"1","title":"boune","value":"3"},{"id":"2","title":"check","value":"4"},{"id":"3","title":"boune","value":"5"}]';
$json_data = json_decode($json,true);
function accumulateValuesByTitle($json_data){
$hash = [];
foreach($json_data as $each_record){
if(isset($hash[$each_record['title']])){
$hash[$each_record['title']]['value'][] = $each_record['value'];
if($hash[$each_record['title']]['id'] > $each_record['id']){
$hash[$each_record['title']]['id'] = $each_record['id'];
}
}else{
$hash[$each_record['title']] = $each_record;
$hash[$each_record['title']]['value'] = [$hash[$each_record['title']]['value']];
}
}
return array_values($hash);
}
$modified_data = accumulateValuesByTitle($json_data);
echo json_encode($modified_data);
Good morning, given the below data structure (in JSON for ease of reading)
[
{
"parent": "root",
"active": "1",
"label": "Index",
"route": "/",
"children": [
{
"parent": "/",
"active": "1",
"label": "Products",
"route": "/products",
"children": [
{
"parent": "/products",
"active": "0",
"label": "Test",
"route": "/test"
}
]
}
]
},
{
"parent": "root",
"active": "1",
"label": "404",
"route": "/404"
},
{
"parent": "root",
"active": "1",
"label": "Login",
"route": "/login"
}
]
I am having major trouble returning from a function the following structure:
[
{
"parent": "root",
"active": "1",
"label": "Index",
"route": "/"
},
{
"parent": "/products",
"active": "0",
"label": "Test",
"route": "/test"
},
{
"parent": "/",
"active": "1",
"label": "Products",
"route": "/products"
},
{
"parent": "root",
"active": "1",
"label": "404",
"route": "/404"
},
{
"parent": "root",
"active": "1",
"label": "Login",
"route": "/login"
}
]
Essentially I want to recurse through all the children and populate a new array with every parent and child in the nested arrays, I have tried array_merge, RecursiveIteratorIterator, iterator_to_array, array_map, but it always comes unstuck on the recursion. I managed to do it when the children were only one level deep but two or more simply breaks down.
Easy-peasy
function flatten($items, &$r) {
foreach($items as $item) {
$c = isset($item->children) ? $item->children : null;
unset($item->children);
$r []= $item;
if($c)
flatten($c, $r);
}
}
flatten(json_decode($json), $r);
print_r($r);
This accumulates results in one single buffer, passed by reference. This is far more efficient than building a whole new array on each iteration, which is basically a variation of the Shlemiel the painter's algorithm.
If you prefer functional approach, you can use generators:
function flatten($items) {
foreach($items as $item) {
$c = isset($item->children) ? $item->children : [];
unset($item->children);
yield $item;
foreach(flatten($c) as $child)
yield $child;
}
}
foreach(flatten(json_decode($json)) as $item)
print_r($item);
Not very hard:
function flatten(array $array) {
$branch = [];
foreach ($array as $item) {
$children = [];
if (isset($item['children']) && is_array($item['children'])) {
$children = flatten($item['children']);
unset($item['children']);
}
$branch = array_merge($branch, [$item], $children);
}
return $branch;
}
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.
After querying the DB for comments that are nested in a closure table, like Bill Karwin suggests here What is the most efficient/elegant way to parse a flat table into a tree?, I now get the following datastructure from SQL:
"comments": [
{
"id": "1",
"breadcrumbs": "1",
"body": "Bell pepper melon mung."
},
{
"id": "2",
"breadcrumbs": "1,2",
"body": "Pea sprouts green bean."
},
{
"id": "3",
"breadcrumbs": "1,3",
"body": "Komatsuna plantain spinach sorrel."
},
{
"id": "4",
"breadcrumbs": "1,2,4",
"body": "Rock melon grape parsnip."
},
{
"id": "5",
"breadcrumbs": "5",
"body": "Ricebean spring onion grape."
},
{
"id": "6",
"breadcrumbs": "5,6",
"body": "Chestnut kohlrabi parsnip daikon."
}
]
Using PHP I would like to restructure this dataset, so the comments are nested like this:
"comments": [
{
"id": "1",
"breadcrumbs": "1",
"body": "Bell pepper melon mung."
"comments": [
{
"id": "2",
"breadcrumbs": "1,2",
"body": "Pea sprouts green bean."
"comments": [
{
"id": "4",
"breadcrumbs": "1,2,4",
"body": "Rock melon grape parsnip."
}
]
},
{
"id": "3",
"breadcrumbs": "1,3",
"body": "Komatsuna plantain spinach sorrel."
}
]
},
{
"id": "5",
"breadcrumbs": "5",
"body": "Ricebean spring onion grape."
"comments": [
{
"id": "6",
"breadcrumbs": "5,6",
"body": "Chestnut kohlrabi parsnip daikon."
}
]
}
]
I have hacked together a solution, but it seems over complex, and I have a feeling that there is some clever solution out there to do this in an elegant and efficient way, but I dont know how?
Assuming you fetch all your data into an array indexed by the "id":
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$nodes[$row["id"]] = $row;
}
I tested the following and it works to produce the JSON output you want:
foreach ($nodes as &$node) {
$parent = array_shift(array_slice(explode(",",$node["breadcrumbs"]), -2, 1));
if ($parent == $node["id"]) {
$forest["comments"][] = &$node;
} else {
$nodes[$parent]["comments"][] = &$node;
}
}
print json_encode($forest, JSON_PRETTY_PRINT);
I would suggest a 2 stage approach.
Stage 1 : Build an nested array
Stage 2 : Convert array to JSON
Stage 1 can be handled simply by creating your elements based on your breadcrumbs.
For example, for "breadcrumbs": "1,2,4"
$comments_array[1][2][4] = $current_element_from_flat_array;
I'm not sure what the most elegant way to get to the above code is, perhaps by parsing the breadcrumbs into its element and having if-else statements based in this. It might be functional, but It's probably not the most elegant code.
$breadcrumbs_list = explode(",", $pizza);
if (count($breadcrumbs_list) == 2)
$comments_array[$breadcrumbs_list[1]][$breadcrumbs_list[2]] = $current_element_from_flat_array;
else if (count($breadcrumbs_list) == 3)
$comments_array[$breadcrumbs_list[1]][$breadcrumbs_list[2]][$breadcrumbs_list[1]] = $current_element_from_flat_array;
Stage 2 can be done using json_encode() provided by PHP.
$tree = array('NULL' => array('children' => array()));
foreach($array as $item){
if(isset($tree[$item['id']])){
$tree[$item['id']] = array_merge($tree[$item['id']],$item);
} else {
$tree[$item['id']] = $item;
}
$parentid = is_null($item['id_parent']) ? 'NULL' : $item['id_parent'];
if(!isset($tree[$parentid])) $tree[$parentid] = array('children' => array());
//this & is where the magic happens: any alteration to $tree[$item['id']
// will reflect in the item $tree[$parentid]['children'] as they are the same
// variable. For instance, adding a child to $tree[$item['id']]['children]
// will be seen in
// $tree[$parentid]['children'][<whatever index $item['id'] has>]['children]
$tree[$parentid]['children'][] = &$tree[$item['id']];
}
$result = $tree['NULL']['children'];
//always unset references
unset($tree);
This solution needs a little polishing. Hope it helps.