Re-looping through an array (PHP) - php

I have a strange array. I get some objects that have children, and then I have some objects that are the id's of the children.
array {
"1": {
"children": [
10,
11,
],
"parent_id": null,
}
}
"2": {
"children": [
12,
13,
]
"parent_id": null,
}
"10": {
"name": Tom,
"parentid": 1,
}
"11": {
"name": Peter,
"parentid": 1,
}
}
I'm trying to first list out the objects if they have children via a foreach.
foreach ($array as $key) {
if (parent_id === null){
echo id;
}
}
So I get a list that looks like this:
1
2
(no 10 and 11)
But now what I want to do is list the name of the children under their parent, so it ends up something like this:
1
Tom
Peter
2
I have an array of the children ids, I'm just not sure how to reloop through the original array for the names.

Will assume your array is one level deep, a parent_id == null signifies a parent and there are no possible orphan elements that should be displayed:
foreach($array as $key => $value) {
if ($value['parent_id'] === null) {
echo $key;
// we got a parent, iterate through it's children
foreach($value['children'] as $childId) {
echo $array[$childId]['name'];
}
}
}
May want to add some empty checks, just to make sure all keys exist in the array.

Related

How insert Multiple Array item into One Array in PHP

i want to add multiple Array item into One Array Object in PHP
i have array like below :
[
{
"name": "AAA"
},
{
"family": "BBB"
},
{
"job": "CCC"
}
]
And i need to Convert like below:
{
"name": "AAA",
"family": "BBB",
"job": "CCC"
}
Array Data maybe changed , but , i write this code for explain my problem :
$RetArray=array();
$Array_Test=array(array('name'=>'AAA'),array('family'=>'BBB'),array('job'=>'CCC'));
foreach ($Array_Test as $json_item){
foreach ($json_item as $key=>$value){
array_push($RetArray,array($key => $value));
}
}
echo json_encode($RetArray);
But this code returns the same as the first array!
I want to return every item into one array.
Try this:
$RetArray=[];
$SrcArray=[
["name"=>"AAA"],
["family"=>"BBB"],
["job"=>"CCC"],
];
foreach($SrcArray as $item){
$RetArray=array_merge($RetArray,$item);
}
echo json_encode($RetArray);
Here is what it got: https://3v4l.org/kZJ2T
you can use array_merge() or array_push()

Find the value of a key in an unknown multilevel array in PHP

I have a use defined json string inside a database.
The JSON string has lots of levels. I know my user will define a kay called "basevalue" and place it somewhere in the json.
The problem is, I don't know ahead of time where in the JSON it will be placed, and every use is likely to place is in different places in the array, perhaps at different levels.
This is an example of the JSON data being saved by the user:
{
"name": "",
"type": "layout",
"children": [
{
"name": "",
"type": "section",
"children": [
{
"name": "",
"type": "row",
"children": [
{
"name": "",
"type": "column",
"props": {
},
"children": []
},
{
"type": "column",
"children": [
{
"type": "itemdata",
"props": {
**"basevalue": "100",**
},
"children": []
}
]
}
]
}
]
}
I'm converting this data to an array using json_decode:
$json = json_decode($json, true);
No I need to search through the array, and find the key of 'basevalue' and then get whatever value the user has input, in the case above that would be '100'.
So to the issue is, I have no idea what 'node' the 'basevalue' key will be. It could be 40 deep, it could be in the first 'children' node.
This is up to the user.
So how do I take any version of the JSON string about and return the '100'?
Many thanks.
You can recursively iterate over the data and get the value of the key basevalue. To make this search faster, we can adopt an early exit approach similar to breadth first search. By this, we call add all values who are arrays in a queue and continue our search for the key basevalue and later on deal with pending queue. This would be faster than basic recursion because a lot of times it's possible that key was on the same level but we searched all the way down on all other trees which proved out to be trivial.
Snippet:
function getBaseValue($arr,$search_key){
$pending_calls = [];
foreach($arr as $key => $value){
if(is_array($value)){
$pending_calls[] = $value; // queue them for later judgement
}else if($search_key === $key){
return $value;
}
}
foreach($pending_calls as $call){
$returned_val = getBaseValue($call,$search_key);
if($returned_val !== false) return $returned_val;
}
return false;
}
echo getBaseValue($arr,'basevalue');
Demo: https://3v4l.org/gdLK1

Search multidimensional array with Key name and return values as result

I am PHP beginner so please be patient with me. I spent couple of hours going through many threads already on multidimensional arrays search but none of them fits my situation. Sounds really simple but kind of stuck as I want to search by key name and retrieve values against it.
Tried some methods like array_column but returns an empty array.
I simply want to loop through array finding key name as: "largeImageURL" from all the array elements and want to return its values.
{
"total": 4692,
"totalHits": 500,
"hits": [
{
"id": 195893,
"pageURL": "https://pixabay.com/en/blossom-bloom-flower-195893/",
"type": "photo",
"tags": "blossom, bloom, flower",
"previewURL": "https://cdn.pixabay.com/photo/2013/10/15/09/12/flower-195893_150.jpg"
"previewWidth": 150,
"previewHeight": 84,
"webformatURL": "https://pixabay.com/get/35bbf209e13e39d2_640.jpg",
"webformatWidth": 640,
"webformatHeight": 360,
"largeImageURL": "https://pixabay.com/get/ed6a99fd0a76647_1280.jpg",
"fullHDURL": "https://pixabay.com/get/ed6a9369fd0a76647_1920.jpg",
"imageURL": "https://pixabay.com/get/ed6a9364a9fd0a76647.jpg",
"imageWidth": 4000,
"imageHeight": 2250,
"imageSize": 4731420,
"views": 7671,
"downloads": 6439,
"favorites": 1,
"likes": 5,
"comments": 2,
"user_id": 48777,
"user": "Josch13",
"userImageURL": "https://cdn.pixabay.com/user/2013/11/05/02-10-23-764_250x250.jpg",
},
{
"id": 73424,
...
},
...
]
}
First of all, you have to convert your JSON object to an array and compare like below.
$results = json_decode($your_array);
$match_result = [];
foreach($results['hits'] as $result) {
if (isset($result['largeImageURL']) {
$match_result [] = $result['largeImageURL'];
}
}
print_r($match_result);
You have to decode your JSON response into an array and loop through hits array till you find the key and return the data.
$returnArr = array();//to store values of largeImageURL
$json = "<json response>";//your json string here
$decoded_json = json_decode($json, true);//convert json to an array
//now we will loop through hits
foreach($decoded_json['hits'] as $hit){
$returnArr[] = $hit['largeImageURL'];
}
print_r($returnArr);

Get whole array with keys and values where key equals value

I have arrays in my JSON like this:
[
{
"id":"bobbys_burgers",
"is_enabled":true,
"name":"Bobbys Burgers",
"supported_transactions":[
"222",
"111",
"333"
],
"enrollment_required":[
],
"restricted_transactions":[
"123"
]
},
{
"id":"randys_sandwich",
"is_enabled":true,
"name":"Randys Sandwich",
"supported_transactions":[
"321"
],
"enrollment_required":[
],
"restricted_transactions":[
]
},
]
I want to get all the keys of the whole array where id = randys_sandwich. for example, i want to search for id == randys_sandwich and return the is_enabled, name, supported_transactions, etc AND their values from that array. how can i do that in php?
You need to json_decode your array then loop through the objects in your array find the one with the id you're looking for.
$array = json_decode($json, true);
foreach ($item in $array) {
if ($item['id'] == 'randys_sandwich') {
var_dump($item);
break; // Once you've found the item no need to continue the loop
}
}

PHP While Loop Resolve

I am having a bit of trouble resolving things in a PHP while loop. Basically I have an array in this form (easier to represent in JSON for brevity)
{
"node2": {
"rowid": "2",
"label": "Eco-Lights - Compact Fluorescent Lamps (CFL)",
"slug": "eco-lights-compact-fluorescent-lamps-cfl",
"prefix": "/categories",
"parent": "55",
"path": null,
"weight": "100",
"featured": "0",
"active": "0"
},
"node3": {
"rowid": "3",
"label": "Light Movers, Hangers and Accessories",
"slug": "light-movers-hangers-and-accessories",
"prefix": "/categories",
"parent": "59",
"path": null,
"weight": "100",
"featured": "0",
"active": "0"
}
}
This array is about 150 elements give or take a few. The key of the node is simply "node"+rowid for ease of lookup (in the next part)
What I am trying to do is take any node and go right up until its parent is zero (i/e has no parents) and on each iteration grab the label and slug of the parent element.
So far I have done this using a while loop as below. $this->categories is the array as above. The trouble is that the loop is incorrect and it's hitting 4gb of memory and doing around 5,000 loops for an array of 150 elements with roughly one parent each so it should be something less than 500 iterations.
public function ResolveCategoryUrl($id) {
$element=$element=$this->categories['node'.$id];
$parent=$element['parent'];
while(1) {
$prev=$element;
$element=$this->categories['node'.$element['parent']];
$parts[]=$element['slug'];
$breadcrumbs[]=['label'=>$element['label'],'url'=>$element['prefix'].$element['path'].$element['data']['url_postfix']];
$parent=$element['parent'];
if($parent<=1) {
break;
}
}
return [
'path'=>array_reverse($parts),
'breadcrumbs'=>$breadcrumbs
];
}
I cannot figure out how to tell PHP to take an element and work backward up to its parent until parent = 0 then return what I want from the function.
Sorry if the explanation is difficult, I have no other way to explain it!
This sounds like a basic reverse tree search (starting at a leaf node and working back up to the root). This is accomplished easily when using recursion. Something along these lines is probably what you're looking for:
function visitNode($nodeNum, $output = [])
{
$output[] = $nodeNum;
$element = $this->categories['node' . $nodeNum];
$parent = $element['parent'];
// Recursive case: keep searching until you're at the parent
if($parent != 0) {
return visitNode($parent, $output);
}
// Base Case
return $output;
}
The output of this function will be an array of your ids representing the chain of nodes visited on the search from your leaf node to its parent. The output of calling this on a parent node will be an array with a single entry.
You may need to put in another case to ensure that the category node + $nodeNum actually exists, but it may make more sense for that to be elsewhere.
Update
To use this function to solve your particular problem and build the breadcrumbs (getting the specific output you require):
$path = [];
$breadcrumbs = [];
$myStartNode = '3';
$pathIds = array_reverse(visitNode($myStartNode));
foreach($pathIds as $pathId) {
$element = $this->categories[$pathId];
$path[] = $element->slug;
$breadcrumbs[] = [
'label' => $element['label'],
'url' => $element['prefix'].$element['path'].$element['data']['url_postfix']
];
}
return [ 'path' => $path, 'breadcrumbs' => $breadcrumbs ];
The visitNode function above was mentioned solely to try to help solve the issue I believe that you're having difficulty with. Also, it's probably best to keep that logic outside what you're trying to do because you may be required to perform that same sort of tree traversal in another context that requires different output.
You said there is no [node0].
If you are certain that all nodes are in order (no missing numbers), then you can do something like:
$i = count($arrayData) //will give you number of nodes
And you can loop through your array with something like:
for ($a=$i, $a>=1; $a--)
{
$b = $arrayData[$a];
$label = $b['label'];
}

Categories