Update multidimensional array value depending on other sibling value - php

I have array this can be up to n element.
(
[children] => Array
(
[0] => Array
(
[id] => nhbs0123620cf897
[title] => Introduction
[children] => Array
(
[0] => Array
(
[id] => bylff0a76617c8
[title] => Courent3
[children] => Array
(
)
)
[1] => Array
(
[id] => xavs26efa2f51eb
[title] => Chapter
[children] => Array
(
)
)
[2] => Array
(
[id] => iezkd241d9d90
[title] => external
[children] => Array
(
)
)
[3] => Array
(
[id] => gmzh439c4f50
[title] => audio
[children] => Array
(
)
)
[4] => Array
(
[id] => niugd4e18b0
[title] => url
[children] => Array
(
)
)
[5] => Array
(
[id] => unpgdb1b7694
[title] => new
[children] => Array
(
)
)
[6] => Array
(
[id] => ssvc2025c0c8a
[title] => simple
[children] => Array
(
[0] => Array
(
[id] => ssvc2025c0c
[title] => later
[children] => Array
(
)
)
)
)
)
)
[1] => Array
(
[id] => rwtae5d9482
[title] => Summary
[children] => Array
(
[0] => Array
(
[id] => ssvc2025c0
[title] => later
[children] => Array
(
)
)
)
)
[2] => Array
(
[id] => rwtae5d9482709
[title] => Course
[children] => Array
(
)
)
)
)
Here I want to update title value depending on id for each element in array.
What i have tried
1 used array_walk_recursive here i can update data but while updating not able to check id value .
array_walk_recursive(array, function(&$value, $key) {
// not able to check if id == 'something' .this is what i need
if ($key == 'title') {
$value = 'updated data';
}
});
Second tried in for each loop but not able to hold array index to get actual array
function myfun($array,&$out){
foreach($array['children'] as $key=>$val){
if(!empty($val['children'])){
$out['children'][$key]['title'] = $val['title']; // this is not right key
$this->myfun($val,$out['children']);
}else{
$out['children'][$key]['title'] = $val['title']; // this is not right key
}
}
}
here also not able to return array in $out array.
Only thing i have that children key using this if any function can be written.
I am hoping this should be possible in php array functions.

You are close - all you need is to use the & - this will send the array as reference so any change on him will be on the original array. Can look in PHP manual for more knowledge.
Consider the following:
$arr = [["id" => 1, "title" => "aaa", "children" => []], ["id" => 2, "title" => "bbb", "children" => [["id" => 3, "title" => "ccc", "children" => []]]]];
function modifyTitle(&$arr, $id, $newVal) {
foreach($arr as &$e) {
if ($e["id"] == $id)
$e["title"] = $newVal;
modifyTitle($e["children"], $id, $newVal);
}
}
modifyTitle($arr, 3, "zzz");
print_r($arr); // now the original array children changed
Live example: https://3v4l.org/ZbiB9

Related

Flatten Array php

I'm trying to flat a multidimensional array to a given specific format.
I have a tree that is saved as a nested array, which is ok, but the function given to render the array in the UI expects only one array and, per each child, an independent array. Instead of the nested array, each option should be at the same level.
This is how my var_dump of my array:
(
[id] => 1
[name] => some data.
[emoji] => 🐕
[parent_id] =>
[children] => Array
(
[0] => Array
(
[id] => 2
[name] => Food
[emoji] => 🥩
[parent_id] => 1
[children] => Array
(
)
)
[1] => Array
(
[id] => 3
[name] => some other data
[emoji] => 😌
[parent_id] => 1
[children] => Array
(
[0] => Array
(
[id] => 4
[name] => Massages
[emoji] => 💆
[parent_id] => 3
[children] => Array
(
)
)
[1] => Array
(
[id] => 5
[name] => Games
[emoji] => 🎾
[parent_id] => 3
[children] => Array
(
)
)
)
)
)
)
)
And the expected result should be:
0] => Array
(
[id] => 1
[name] => Rusty Corp.
[emoji] => 🐕
[parent_id] =>
)
[1] => Array
(
[id] => 2
[name] => Food
[emoji] => 🥩
[parent_id] => 1
)
[2] => Array
(
[id] => 3
[name] => Canine Therapy
[emoji] => 😌
[parent_id] => 1
)
[3] => Array
(
[id] => 4
[name] => Massages
[emoji] => 💆
[parent_id] => 3
)
[4] => Array
(
[id] => 5
[name] => Games
[emoji] => 🎾
[parent_id] => 3
)
I tried different approaches like array_merge or custom flattening function but can't nail with the expected results, any suggestions?
Edit:
This is my flatten function:
private function flatten_array( array $array ) {
$return = array();
array_walk_recursive(
$array,
function( $a ) use ( &$return ) {
$return[] = $a;
}
);
return $return;
}
Here is a recursive function that will flatten the array, it will not take into account the null value of parent_id on the root element. Also the flattened array will start with the most nested elements at the start of the array and root element at the end.
function flatten_array($array, $flattened = []) {
$current = [];
foreach ($array as $key => $value) {
if (is_array($value))
$flattened = array_merge($flattened, flatten_array($value));
else
$current[$key] = $value;
}
$flattened[] = $current;
return array_filter($flattened);
}

sort an array with another array which has sorted keys

How to sort an 1st array with 2nd array which has sorted keys in 2nd array without using any loop.
1st Array.
$chunk = array(
[0] => Array
(
[id] => 212
[order] => 1
[title] => fdfdfdfdf
)
[1] => Array
(
[id] => 5
[order] => 2
[title] =>
)
[2] => Array
(
[id] => 781
[order] => 3
[title] =>
)
)
2nd array with sorted keys of 1st array.
$sort = array
(
[2] => 2
[0] => 0
[1] => 1
)
You could use array_map for that:
$arr = array_map(function($val) use($chunk){
return $chunk[$val];
}, $sort);
This is the output:
Array
(
[2] => Array
(
[id] => 781
[order] => 3
[title] =>
)
[0] => Array
(
[id] => 212
[order] => 1
[title] => fdfdfdfdf
)
[1] => Array
(
[id] => 5
[order] => 2
[title] =>
)
)
Now, if you want the keys to be 0,1,2..., you can use array_values, after mapping:
$arr = array_values($arr);
And the output:
Array
(
[0] => Array
(
[id] => 781
[order] => 3
[title] =>
)
[1] => Array
(
[id] => 212
[order] => 1
[title] => fdfdfdfdf
)
[2] => Array
(
[id] => 5
[order] => 2
[title] =>
)
)
Of course, there is no function for this. You'll have to do something similar
<?php
$chunk = [
// data
];
$sorted = [];
$sort = [
// ordered keys
];
foreach($sort as $keyToFind) {
foreach($chunk as $arrayElement) {
if($arrayElement['id'] == $keyToFind)) {
$sorted[$keyToFind] = $arrayElement;
}
}
}
As you can see, this is a bit time and ressources consumming because of the two imbricated foreaches. Let's hope your arrays are not so big

Merge Array by value PHP

I have a problem, I would like to merge arrays by value. Below is a entry example, the entry array have a 100 records
Array
(
[0] => Array
(
[id] => 1
[code] => dfrr5tv5t5vt5
[status] => online
)
[1] => Array
(
[id] => 2
[code] => e32e3e2e2323e23e
[status] => online
)
[2] => Array
(
[id] => 1
[desc] => Some_description
)
[3] => Array
(
[id] => 2
[desc] => Some_description_2
)
....
)
I would like to get the following result through merge array by [id]
Array
(
[0] => Array
(
[id] => 1
[code] => dfrr5tv5t5vt5
[status] => online
[desc] => Some_description
)
[1] => Array
(
[id] => 2
[code] => e32e3e2e2323e23e
[status] => online
[desc] => Some_description_2
)
....
)
Use assocative arrays. Use $row["id"] as associative index.
$result = [];
foreach ($arr as $row) {
$result[$row["id"]] = isset($result[$row["id"]]) ? array_merge($result[$row["id"]], $row) : $row;
}
$result = array_values($result); // optional, this removes associative keys

how to get values a long array with size zero

I have following array from google api and wanted to get id only. How do i get id's from following. when i try to get size it gives me size zero.
Google_Service_Drive_FileList Object ( [collection_key:protected] => items
[internal_gapi_mappings:protected] => Array ( ) [etag] => [itemsType:protected]
=> Google_Service_Drive_DriveFile [itemsDataType:protected] => array [kind] =>
[nextLink] => [nextPageToken] => [selfLink] => [modelData:protected] => Array (
[items] => Array ( [0] => Array ( [id] => 0B0OnHwH_cQckeWZPdXFyRU5aMGs ) [1] =>
Array ( [id] => 0B0OnHwH_cQckaUVORkZaM2NoRXM ) [2] => Array ( [id] =>
1kCQLhEgzgeKO-L57ISWjQL4ctkxT4Gq2wrdzDFbrcac ) [3] => Array ( [id] =>
0B0OnHwH_cQckc3RhcnRlcl9maWxl ) [4] => Array ( [id] => 1-Yhs92vZnvUNArwAcZJZ9xa-
fXZ7ZgRrADyF-ikG1gU ) ) ) [processed:protected] => Array ( ) ) Array ( )
if you mean the object attributes, you can do
$values = array();
$keys = array();
foreach($object as $key=>$value)
{
array_push($keys,$key);
array_push($values,$value);
}
This will give you each object attribute and its corresponding value

array one format to another

I have one array in two format. I want to change array from
Array
(
[step_number] => 4
[app_id] => Array
(
[0] => 2
[1] => 3
)
[formdata] => Array
(
[0] => Array
(
[name] => app_id[]
[value] => 2
)
[1] => Array
(
[name] => app_id[]
[value] => 3
)
[2] => Array
(
[name] => fieldval[2][2][]
[value] => 1
)
[3] => Array
(
[name] => fieldval[3][3][]
[value] => 200
)
[4] => Array
(
[name] => fieldval[3][3][]
[value] => day
)
[5] => Array
(
[name] => title
[value] => new plan
)
[6] => Array
(
[name] => feature_plan
[value] => 3
)
[7] => Array
(
[name] => plan_type
[value] => free
)
[8] => Array
(
[name] => price
[value] =>
)
[9] => Array
(
[name] => sell_type
[value] => us
)
)
)
this format to
Array
(
[app_id] => Array
(
[0] => 2
[1] => 3
)
[fieldval] => Array
(
[2] => Array
(
[2] => Array
(
[0] => 1
)
)
[3] => Array
(
[3] => Array
(
[0] => 200
[1] => day
)
)
)
[title] => new plan
[feature_plan] => 3
[plan_type] => free
[price] =>
[sell_type] => us
)
these are are one array into two format. i have data in to first array format and i want to change that format to second array type format.
please tell me how i am trying this for 2 days but not succeed.
Here is a function you could use to produce that conversion:
function convert_formdata($input) {
$output = array();
foreach($input['formdata'] as $data) {
$keys = preg_split("#[\[\]]+#", $data['name']);
$value = $data['value'];
$target = &$output;
foreach($keys as $key) {
// Get index for "[]" reference
if ($key == '') $key = count($target);
// Create the key in the parent array if not there yet
if (!isset($target[$key])) $target[$key] = array();
// Move pointer one level down the hierarchy
$target = &$target[$key];
}
// Write the value at the pointer location
$target = $value;
}
return $output;
}
You would call it like this:
$output = convert_formdata($input);
See it run on eval.in for the given input. The output is:
array (
'app_id' =>
array (
0 => 2,
1 => 3,
),
'fieldval' =>
array (
2 =>
array (
2 =>
array (
0 => 1,
),
),
3 =>
array (
3 =>
array (
0 => 200,
1 => 'day',
),
),
),
'title' => 'new plan,',
'feature_plan' => 3,
'plan_type' => 'free',
'price' => NULL,
'sell_type' => 'us',
)

Categories