sorting an array which its values are associate array - php

I have an array that its values are associate arrays. I need sort this array based on keys;
$list = array (
array("post_id"=>"2","date"=>"2015","title"=>"title2"),
array("post_id"=>"4","date"=>"2017","title"=>"title4"),
array("post_id"=>"3","date"=>"2016","title"=>"title3"),
array("post_id"=>"1","date"=>"2014","title"=>"title1")
);
For example sorting this array by post_id which means turn that array to this:
$list = array (
array("post_id"=>"1","date"=>"2014","title"=>"title1"),
array("post_id"=>"2","date"=>"2015","title"=>"title2"),
array("post_id"=>"3","date"=>"2016","title"=>"title3"),
array("post_id"=>"4","date"=>"2017","title"=>"title4")
);
I searched this forum and find this code:
function array_sort($array, $on, $order=SORT_ASC){
$new_array = array();
$sortable_array = array();
if (count($array) > 0) {
foreach ($array as $k => $v) {
if (is_array($v)) {
foreach ($v as $k2 => $v2) {
if ($k2 == $on) {
$sortable_array[$k] = $v2;
}
}
} else {
$sortable_array[$k] = $v;
}
}
switch ($order) {
case SORT_ASC:
asort($sortable_array);
break;
case SORT_DESC:
arsort($sortable_array);
break;
}
foreach ($sortable_array as $k => $v) {
$new_array[$k] = $array[$k];
}
}
return $new_array;}
but I cant understand what is it exactly doing.
the topic link is:
Sort PHP multi-dimensional array based on key?

You're not sorting by key, so the example you found won't work for you. A simple usort will do it;
$list = array (
array("post_id"=>"2","date"=>"2015","title"=>"title2"),
array("post_id"=>"4","date"=>"2017","title"=>"title4"),
array("post_id"=>"3","date"=>"2016","title"=>"title3"),
array("post_id"=>"1","date"=>"2014","title"=>"title1")
);
function sortPosts($a, $b)
{
if ($a['post_id'] == $b['post_id']) {
return 0;
}
return ($a['post_id'] < $b['post_id']) ? -1 : 1;
}
usort($list, "sortPosts");
This passes your $lists array into a function and compares each of its values - you can see we're comparing the ['post_id'] value for each.
As the post_id's are strings in your original array, you may need to typecast these as integers, but see how you go.

I use this function :
function aasort (&$array, $key) {
$sorter=array();
$ret=array();
reset($array);
foreach ($array as $ii => $va) {
$sorter[$ii]=$va[$key];
}
asort($sorter);
foreach ($sorter as $ii => $va) {
$ret[$ii]=$array[$ii];
}
$array=$ret;
return $array;
}
$list = array (
array("post_id"=>"2","date"=>"2015","title"=>"title2"),
array("post_id"=>"4","date"=>"2017","title"=>"title4"),
array("post_id"=>"3","date"=>"2016","title"=>"title3"),
array("post_id"=>"1","date"=>"2014","title"=>"title1")
);
$outputArray = aasort($list,"post_id");

Most elegant usually is to use the usort() function combined with a closure.
Take a look at this simple demonstration:
<?php
$list = [
["post_id"=>"2","date"=>"2015","title"=>"title2"],
["post_id"=>"4","date"=>"2017","title"=>"title4"],
["post_id"=>"3","date"=>"2016","title"=>"title3"],
["post_id"=>"1","date"=>"2014","title"=>"title1"]
];
usort(
$list,
function($a, $b) {
return $a['post_id'] < $b['post_id'];
}
);
print_r($list); // First output, descending order
usort(
$list,
function($a, $b) {
return $a['post_id'] > $b['post_id'];
}
);
print_r($list); // Second output, ascending order
Note the reversed comparison operator in the two calls, < versus >...
The output of that obviously is:
First output, descending order:
Array
(
[0] => Array
(
[post_id] => 4
[date] => 2017
[title] => title4
)
[1] => Array
(
[post_id] => 3
[date] => 2016
[title] => title3
)
[2] => Array
(
[post_id] => 2
[date] => 2015
[title] => title2
)
[3] => Array
(
[post_id] => 1
[date] => 2014
[title] => title1
)
)
Second output, ascending order:
Array
(
[0] => Array
(
[post_id] => 1
[date] => 2014
[title] => title1
)
[1] => Array
(
[post_id] => 2
[date] => 2015
[title] => title2
)
[2] => Array
(
[post_id] => 3
[date] => 2016
[title] => title3
)
[3] => Array
(
[post_id] => 4
[date] => 2017
[title] => title4
)
)

That probably wasn't the best answer to chose from that question. Just extract the column to sort on, and sort that to sort the original:
array_multisort(array_column($list, 'post_id'), SORT_ASC, $list);

You can use following code:
<?php
$list = array (
array("post_id"=>"2","date"=>"2015","title"=>"title2"),
array("post_id"=>"4","date"=>"2017","title"=>"title4"),
array("post_id"=>"3","date"=>"2016","title"=>"title3"),
array("post_id"=>"1","date"=>"2014","title"=>"title1")
);
$sorted = array_orderby($list, 'post_id', SORT_ASC);
echo "<pre>";
print_r($sorted);
function array_orderby()
{
$args = func_get_args();
$data = array_shift($args);
foreach ($args as $n => $field) {
if (is_string($field)) {
$tmp = array();
foreach ($data as $key => $row)
$tmp[$key] = $row[$field];
$args[$n] = $tmp;
}
}
$args[] = &$data;
call_user_func_array('array_multisort', $args);
return array_pop($args);
}
?>
It will produce following output:
Array
(
[0] => Array
(
[post_id] => 1
[date] => 2014
[title] => title1
)
[1] => Array
(
[post_id] => 2
[date] => 2015
[title] => title2
)
[2] => Array
(
[post_id] => 3
[date] => 2016
[title] => title3
)
[3] => Array
(
[post_id] => 4
[date] => 2017
[title] => title4
)
)

The function in
OP question does:
first collects all values via $on from the subarray (first foreach) and binds it to the $sortable_array via original_array key $k. Like $list[0]['post_id']; is collect in: $sortable_array[0];
After all values are collected, the array will be sorted DESC or ASC (see switch) with asort, that keeps the index=>value connection. So $sortable_array looks like: Before [0=>2,1=>4,2=>3,3=>1] After [3=>1,0=>2,2=>3,1=>4]
So now the values are sorted and the index can be used in the next step.
In the last foreach a new array is generated. The index $k from the $sortable_array is used to get the subsarrays from the original_array in the new order.
note: This part if (is_array($v)) makes the function behavior not predictable, because it takes just the $v if $v is not an subarray else it would take data from the subarray!!!

Related

php - check multidimensional array for values that exists in more than 1 subarray

Following simplified multidimensional array given:
$input = Array
(
[arr1] => Array
(
[0] => JAN2016
[1] => MAI2013
[2] => JUN2014
}
[arr2] => Array
(
[0] => APR2016
[1] => DEC2013
[2] => JUN2014
}
[arr3] => Array
(
[0] => JAN2016
[1] => MAI2020
[2] => JUN2022
}
)
I want to check for elements, that exists in more than 1 subarray. An ideal output would be:
$output = Array
(
[JUN2014] => Array
(
[0] => arr1
[1] => arr2
)
[JAN2016] => Array
(
[0] => arr1
[1] => arr3
)
)
I'm currently stucked in a nested foreach because i need to look all silblings of the outer foreach and don't know how to accomplish that.
foreach($input as $k=>$values)
{
foreach($values as $value)
{
//check if value exists in array k+1....n
//if true, safe to output.
}
}
You are almost all the way there
$new = [];
foreach($input as $k=>$values) {
foreach($values as $value) {
$new[$value][] = $k;
}
}
The $new array should look just as you want it
Extended solution which filters subarrays:
$newArray = [];
foreach($input as $k=>$values)
{
foreach($values as $value)
{
$newArray[$value][] = $k;
}
}
print_r(array_filter(
$newArray,
function($v) { return 1 < count($v); }
));
Sample fiddle here.

How do I add it all up by the `index` key in a PHP Array?

I am using PHP and I have an array
$nnarray = Array (
[9] => Array (
[1] => Array (
[2] => 433
[6] => 2
[4] => 101
)
[3] => Array (
[6] => 999
)
)
[14] => Array (
[2] => Array (
[2] => 0
[6] => 2
)
)
)
How do I add it all up by the index key? Output I would like as below
Array (
[9] => 1535
)
[14] => 2
)
)
1535 = 433+2+101+999 (All value under [9])
Now I using the following script to get the result, is it have another effective way?
foreach($nnarray as $key => $value){
foreach($nnarray[$key] as $nkey => $nvalue){
foreach($nnarray[$key][$nkey] as $nnkey => $nnvalue){
$newarray[$key] = $newarray[$key]+$nnvalue;
}
}
}
print_r($newarray);
You are confusing keys and values !
$newarray= array(); // create a new array to sum up
foreach ($array as $key1 => $valueArray1) { // looping through main array
$resultArray[$key1] = 0; // setting initial value to 0.
foreach ($valueArray1 as $key2 => $valueArray2) { // looping thru inner array
foreach ($valueArray2 as $key => $value) { // looping thru innermost array
$newarray[$key1] += $value;
}
}
}
var_dump($newarray);
And the result will be
array(2) {
[9]=>
int(1535)
[14]=>
int(2)
}
Shorter version, requires >= PHP7.4.0
map sum => map sum
$result = array_map(fn($v) => array_sum(array_map(fn($v) => array_sum($v), $v)), $data);
Result:
Array
(
[9] => 1535
[14] => 2
)
https://3v4l.org/04WcF
A few exotic options.
Iterators:
$result = array_map(function($val)
{
return array_sum(iterator_to_array(new \RecursiveIteratorIterator(new \RecursiveArrayIterator($val))));
}, $array);
Array walking:
$result = array_map(function($val)
{
array_walk_recursive($val, function($v) use (&$sum) { $sum += $v; });
return $sum;
}, $array);

Sort array values based on parent/child relationship

I am trying to sort an array to ensure that the parent of any item always exists before it in the array. For example:
Array
(
[0] => Array
(
[0] => 207306
[1] => Bob
[2] =>
)
[1] => Array
(
[0] => 199730
[1] => Sam
[2] => 199714
)
[2] => Array
(
[0] => 199728
[1] => Simon
[2] => 207306
)
[3] => Array
(
[0] => 199714
[1] => John
[2] => 207306
)
[4] => Array
(
[0] => 199716
[1] => Tom
[2] => 199718
)
[5] => Array
(
[0] => 199718
[1] => Phillip
[2] => 207306
)
[6] => Array
(
[0] => 199720
[1] => James
[2] => 207306
)
)
In the above array this "fails" as [1][2] (Sam) does not yet exist and nor does [4][2] (Tom).
The correct output would be as, in this case, as both Sam and Tom's parents already exist before they appear in the array:
Array
(
[0] => Array
(
[0] => 207306
[1] => Bob
[2] =>
)
[1] => Array
(
[0] => 199714
[1] => John
[2] => 207306
)
[2] => Array
(
[0] => 199730
[1] => Sam
[2] => 199714
)
[3] => Array
(
[0] => 199728
[1] => Simon
[2] => 207306
)
[4] => Array
(
[0] => 199718
[1] => Phillip
[2] => 207306
)
[5] => Array
(
[0] => 199716
[1] => Tom
[2] => 199718
)
[6] => Array
(
[0] => 199720
[1] => James
[2] => 207306
)
)
I found an answer https://stackoverflow.com/a/12961400/1278201 which was very close but it only seems to go one level deep (i.e. there is only ever one parent) whereas in my case there could be 1 or 10 levels deep in the hierarchy.
How do I sort the array so no value can appear unless its parent already exists before it?
This will trivially order the array (in O(n)) putting first all those with no parent, then these whose parent is already in the array, iteratively, until there's no children having the current element as parent.
# map the children by parent
$parents = ['' => []];
foreach ($array as $val) {
$parents[$val[2]][] = $val;
}
# start with those with no parent
$sorted = $parents[''];
# add the children the current nodes are parent of until the array is empty
foreach ($sorted as &$val) {
if (isset($parents[$val[0]])) {
foreach ($parents[$val[0]] as $next) {
$sorted[] = $next;
}
}
}
This code requires PHP 7, it may not work in some cases under PHP 5. - for PHP 5 compatibility you will have to swap the foreach ($sorted as &$val) with for ($val = reset($sorted); $val; $val = next($sorted)):
# a bit slower loop which works in all versions
for ($val = reset($sorted); $val; $val = next($sorted)) {
if (isset($parents[$val[0]])) {
foreach ($parents[$val[0]] as $next) {
$sorted[] = $next;
}
}
}
Live demo: https://3v4l.org/Uk6Gs
I have two different version for you.
a) Using a "walk the tree" approach with recursion and references to minimize memory consumption
$data = [
[207306,'Bob',''], [199730,'Sam',199714],
[199728,'Simon',207306], [199714,'John',207306],
[199716, 'Tom',199718], [199718,'Phillip',207306],
[199720,'James',207306]
];
$list = [];
generateList($data, '', $list);
var_dump($list);
function generateList($data, $id, &$list) {
foreach($data as $d) {
if($d[2] == $id) {
$list[] = $d; // Child found, add it to list
generateList($data, $d[0], $list); // Now search for childs of this child
}
}
}
b) Using phps built in uusort()function (seems only to work up to php 5.x and not with php7+)
$data = [
[207306,'Bob',''], [199730,'Sam',199714],
[199728,'Simon',207306], [199714,'John',207306],
[199716, 'Tom',199718], [199718,'Phillip',207306],
[199720,'James',207306]
];
usort($data, 'cmp');
var_dump($data);
function cmp($a, $b) {
if($a[2] == '' || $a[0] == $b[2]) return -1; //$a is root element or $b is child of $a
if($b[2] == '' || $b[0] == $a[2]) return 1; //$b is root element or $a is child of $b
return 0; // both elements have no direct relation
}
I checked this works in PHP 5.6 and PHP 7
Sample array:
$array = Array(0 => Array(
0 => 207306,
1 => 'Bob',
2 => '',
),
1 => Array
(
0 => 199730,
1 => 'Sam',
2 => 199714,
),
2 => Array
(
0 => 199728,
1 => 'Simon',
2 => 207306,
),
3 => Array
(
0 => 199714,
1 => 'John',
2 => 207306,
),
4 => Array
(
0 => 199716,
1 => 'Tom',
2 => 199718,
),
5 => Array
(
0 => 199718,
1 => 'Phillip',
2 => 207306,
),
6 => Array
(
0 => 199720,
1 => 'James',
2 => 207306,
),
);
echo "<pre>";
$emp = array();
//form the array with parent and child
foreach ($array as $val) {
$manager = ($val[2] == '') ? 0 : $val[2];
$exist = array_search_key($val[2], $emp);
if ($exist)
$emp[$exist[0]][$val[0]] = $val;
else
//print_R(array_search_key(199714,$emp));
$emp[$manager][$val[0]] = $val;
}
$u_emp = $emp[0];
unset($emp[0]);
//associate the correct child/emp after the manager
foreach ($emp as $k => $val) {
$exist = array_search_key($k, $u_emp);
$pos = array_search($k, array_keys($u_emp));
$u_emp = array_slice($u_emp, 0, $pos+1, true) +
$val +
array_slice($u_emp, $pos-1, count($u_emp) - 1, true);
}
print_R($u_emp); //print the final result
// key search function from the array
function array_search_key($needle_key, $array, $parent = array())
{
foreach ($array AS $key => $value) {
$parent = array();
if ($key == $needle_key)
return $parent;
if (is_array($value)) {
array_push($parent, $key);
if (($result = array_search_key($needle_key, $value, $parent)) !== false)
return $parent;
}
}
return false;
}
Find the below code that might be helpful.So, your output is stored in $sortedarray.
$a=array(array(207306,'Bob',''),
array (199730,'Sam',199714),
array(199728,'Simon',207306),
array(199714,'John',207306),
array(199716,'Tom',199718),
array(199718,'Phillip',207306),
array(199720,'James',207306));
$sortedarray=$a;
foreach($a as $key=>$value){
$checkvalue=$value[2];
$checkkey=$key;
foreach($a as $key2=>$value2){
if($key<$key2){
if ($value2[0]===$checkvalue){
$sortedarray[$key]=$value2;
$sortedarray[$key2]=$value;
}else{
}
}
}
}
print_r($sortedarray);
What about this approach:
Create an empty array result.
Loop over your array and only take the items out of it where [2] is empty and insert them into result.
When this Loop is done you use a foreach-Loop inside a while-loop. With the foreach-Loop you take every item out of your array where [2] is already part of result. And you do this as long as your array contains anything.
$result = array();
$result[''] = 'root';
while(!empty($yourArray)){
foreach($yourArray as $i=>$value){
if(isset($result[$value[2]])){
// use the next line only to show old order
$value['oldIndex'] = $i;
$result[$value[0]] = $value;
unset($yourArray[$i]);
}
}
}
unset($result['']);
PS: You may run into trouble by removing parts of an array while walking over it. If you do so ... try to solve this :)
PPS: Think about a break condition if your array have an unsolved loop or a child without an parent.
you can use your array in variable $arr and use this code it will give you required output.
function check($a, $b) {
return ($a[0] == $b[2]) ? -1 : 1;
}
uasort($arr, 'check');
echo '<pre>';
print_r(array_values($arr));
echo '</pre>';

PHP grouping arrays within array by value

Hi I've got a bit of a problem and I can't seem to find the answer. I have an array with arrays in it and want to group these sub arrays into groups based on the same value for a field. This is my code and allows me to sort my arrays based on the arrays inside values. How do I group the result based on shared values? I probably won't know all the values as some are based on date and I want to for instance group all per day/month
if($filter == "ORDER BY TODO_REF DESC"){
$type_sort = 0;
};
if($filter == "ORDER BY TODO_PRIO DESC"){
$type_sort = 2;
};
if($filter == "ORDER BY TODO_DEAD DESC"){
$type_sort = 3;
};
function aasort (&$array, $key) {
$sorter=array();
$ret=array();
reset($array);
foreach ($array as $ii => $va) {
$sorter[$ii]=$va[$key];
}
asort($sorter);
foreach ($sorter as $ii => $va) {
$ret[$ii]=$array[$ii];
}
$array=$ret;
}
aasort($test_array, $type_sort);
print_r($test_array);
Current output:
priority
Array
(
[3] => Array
(
[0] => 2
[1] => sdfsdgdfgdfgdfg
[2] => 3
[3] => 2013-05-30 13:53:23
)
[2] => Array
(
[0] => 1
[1] => This must also be done
[2] => 4
[3] => 2013-03-28 12:13:34
)
[1] => Array
(
[0] => 1
[1] => testing this show me 2
[2] => 5
[3] => 2029-02-23 17:27:20
)
[0] => Array
(
[0] => 1
[1] => Do this task and make sure it gets done
[2] => 5
[3] => 2013-06-28 12:12:41
)
)
What I want would be something like this, where they are split into seperate arrays based on sub array key 2:
Array
(
[3] => Array
(
[0] => 2
[1] => sdfsdgdfgdfgdfg
[2] => 3
[3] => 2013-05-30 13:53:23
)
)
Array
(
[2] => Array
(
[0] => 1
[1] => This must also be done
[2] => 4
[3] => 2013-03-28 12:13:34
)
)
Array
(
[1] => Array
(
[0] => 1
[1] => testing this show me 2
[2] => 5
[3] => 2029-02-23 17:27:20
)
[0] => Array
(
[0] => 1
[1] => Do this task and make sure it gets done
[2] => 5
[3] => 2013-06-28 12:12:41
)
)
$array_1 = array();
$array_2 = array();
foreach($test_array as $item) {
if($item[0] == 1) {
$array_1[] = $item;
} elseif($item[0] == 2) {
$array_2[] = $item;
}
}
$final_array = array($array_1, $array_2);
There must be more optimized codes, but this should serve your needs.
array_multisort() is what you're after it will allow you to sort primary array by sub array and maintain the key value link
I use the below for sorting a rather hefty multi-dimensional array based off sort order arrows asc/desc on a table with many columns and sortable columns. Its abit of a mess but you should be able to follow it.
if (strlen($_GET['col'])<1) {
foreach ($dataarray as $key => $row) {
$spend[$key] = $row[6];
}
array_multisort($spend, SORT_DESC, $dataarray);
} else if ($_GET['col']=="spend"){
foreach ($dataarray as $key => $row) {
$spend[$key] = $row[3];
}
if ($_GET['order']=="asc") {
array_multisort($spend, SORT_ASC, $dataarray);
} else {
array_multisort($spend, SORT_DESC, $dataarray);
}
} else if ($_GET['col']=="name"){
foreach ($dataarray as $key => $row) {
$name[$key] = $row[1];
}
if ($_GET['order']=="asc") {
array_multisort($name, SORT_ASC, $dataarray);
} else {
array_multisort($name, SORT_DESC, $dataarray);
}
} else if ($_GET['col']=="avg"){
foreach ($dataarray as $key => $row) {
$avg[$key] = $row[4];
}
if ($_GET['order']=="asc") {
array_multisort($avg, SORT_ASC, $dataarray);
} else {
array_multisort($avg, SORT_DESC, $dataarray);
}
} else if ($_GET['col']=="sites"){
foreach ($dataarray as $key => $row) {
$sites[$key] = $row[5];
}
if ($_GET['order']=="asc") {
array_multisort($sites, SORT_ASC, $dataarray);
} else {
array_multisort($sites, SORT_DESC, $dataarray);
}
} else if ($_GET['col']=="rate"){
foreach ($dataarray as $key => $row) {
$rate[$key] = $row[6];
}
if ($_GET['order']=="asc") {
array_multisort($rate, SORT_ASC, $dataarray);
} else {
array_multisort($rate, SORT_DESC, $dataarray);
}
} else {
foreach ($dataarray as $key => $row) {
$spend[$key] = $row[2];
}
array_multisort($spend, SORT_DESC, $dataarray);
}
Rather than a block of if-elseif-elseif-elseif...else conditions to determine the sorting/grouping column, I always recommend a lookup array followed by a very quick isset() call. I find this syntax to be more succinct, more readable, and easier to maintain.
So that grouped data is sorted properly, sort the data ahead of time (while it is still in its simpler form). usort() with the spaceship operator (php7) will do all of the hardwork for you. Just be sure to pass the $groupsort variable into the function scope with use.
As you iterate the input array, isolate the identifying column value (and prepare it as necessary), then use it as a temporary key to determine the group in which the $row data should be stored.
Finally, use array_values() to remove the temporary identifying keys (if desired).
Code: (Demo)
$filter = "ORDER BY TODO_PRIO DESC";
$lookup = [
"ORDER BY TODO_REF DESC" => 0,
"ORDER BY TODO_PRIO DESC" => 2,
"ORDER BY TODO_DEAD DESC" => 3
];
$groupsort = isset($lookup[$filter]) ? $lookup[$filter] : 0;
$array = [
[1, "Do this task and make sure it gets done", 5, "2013-06-28 12:12:41"],
[1, "testing this show me 2", 5, "2029-02-23 17:27:20"],
[1, "This must also be done", 4, "2013-03-28 12:13:34"],
[2, "sdfsdgdfgdfgdfg", 3, "2013-05-30 13:53:23"],
[2, "Another priority", 3, "2013-03-28 11:11:11"]
];
// sort DESC on $groupsort column values
usort($array, function($a, $b)use($groupsort) { return $b[$groupsort] <=> $a[$groupsort]; });
// group by $groupsort column values
foreach ($array as $row) {
$id = $row[$groupsort]; // just to improve readability
if ($groupsort == 3) { $id = substr($id, 0, 10); } // remove time from datetime stamp
$result[$id][] = $row; // store the current value
}
var_export(array_values($result)); // reindex first level (remove temp keys);
Output:
array (
0 =>
array (
0 =>
array (
0 => 1,
1 => 'Do this task and make sure it gets done',
2 => 5,
3 => '2013-06-28 12:12:41',
),
1 =>
array (
0 => 1,
1 => 'testing this show me 2',
2 => 5,
3 => '2029-02-23 17:27:20',
),
),
1 =>
array (
0 =>
array (
0 => 1,
1 => 'This must also be done',
2 => 4,
3 => '2013-03-28 12:13:34',
),
),
2 =>
array (
0 =>
array (
0 => 2,
1 => 'sdfsdgdfgdfgdfg',
2 => 3,
3 => '2013-05-30 13:53:23',
),
1 =>
array (
0 => 2,
1 => 'Another priority',
2 => 3,
3 => '2013-03-28 11:11:11',
),
),
)

array_values recursive php

Let's say I have an array like this:
Array
(
[id] => 45
[name] => john
[children] => Array
(
[45] => Array
(
[id] => 45
[name] => steph
[children] => Array
(
[56] => Array
(
[id] => 56
[name] => maria
[children] => Array
(
[60] => Array
(
[id] => 60
[name] => thomas
)
[61] => Array
(
[id] => 61
[name] => michelle
)
)
)
[57] => Array
(
[id] => 57
[name] => luis
)
)
)
)
)
What I'm trying to do is to reset the keys of the array with keys children to 0, 1, 2, 3, and so on, instead of 45, 56, or 57.
I tried something like:
function array_values_recursive($arr)
{
foreach ($arr as $key => $value)
{
if(is_array($value))
{
$arr[$key] = array_values($value);
$this->array_values_recursive($value);
}
}
return $arr;
}
But that reset only the key of the first children array (the one with key 45)
function array_values_recursive($arr)
{
$arr2=[];
foreach ($arr as $key => $value)
{
if(is_array($value))
{
$arr2[] = array_values_recursive($value);
}else{
$arr2[] = $value;
}
}
return $arr2;
}
this function that implement array_values_recursive from array like:
array(
'key1'=> 'value1',
'key2'=> array (
'key2-1'=>'value-2-1',
'key2-2'=>'value-2-2'
)
);
to array like:
array(
0 => 'value1',
1 => array (
0 =>'value-2-1',
1 =>'value-2-2'
)
);
You use a recursive approach but you do not assign the return value of the function call $this->array_values_recursive($value); anywhere. The first level works, as you modify $arr in the loop. Any further level does not work anymore for mentioned reasons.
If you want to keep your function, change it as follows (untested):
function array_values_recursive($arr)
{
foreach ($arr as $key => $value)
{
if (is_array($value))
{
$arr[$key] = $this->array_values_recursive($value);
}
}
if (isset($arr['children']))
{
$arr['children'] = array_values($arr['children']);
}
return $arr;
}
This should do it:
function array_values_recursive($arr, $key)
{
$arr2 = ($key == 'children') ? array_values($arr) : $arr;
foreach ($arr2 as $key => &$value)
{
if(is_array($value))
{
$value = array_values_recursive($value, $key);
}
}
return $arr2;
}
Try this ,
function updateData($updateAry,$result = array()){
foreach($updateAry as $key => $values){
if(is_array($values) && count($values) > 0){
$result[$key] = $this->_updateData($values,$values);
}else{
$result[$key] = 'here you can update values';
}
}
return $result;
}
You can used php fnc walk_array_recursive
Here

Categories