Answer the question
In order to leave comments, you need to log in
How to add a new array to the very end of a multidimensional array of arbitrary depth in php?
There is an array of arbitrary depth (up to several hundred nestings), where each element of the array is either another filled array or an empty array. But always an array!
There is a function that bypasses this array, and:
If it finds an empty array "at the edge" (at the bottom) of the depth of a multidimensional array, then it puts another array there.
If it has skidded, then it scrolls further, if it has not skidded and the depth no longer stops.
Array example:
$test_mass['tk98op'] = array('p5ld2se'=>array(),
'38hjp9'=>array('2we8t2'=>array(), '1142ln'=>array()),
'669yo36'=>array('6318u7'=>array('22rv86'=>array(),
'13we42'=>array()), 'jk66d3'=>array()));
function deep($mass, $b = 0)
{
foreach ($mass as $key=>$val)
{
if(is_array($val))
{
if(count($val) == 0)
{
/* не один из этих трех вариантов ничего не дописывает */
//$val = array(1,4,217,432);
//$mass = array_merge($val, array(1,4,217,432));
//$mass[$key] = array(1,4,217,432);
}
deep($val, $b);
}
}
return $mass;
}
Array
(
[tk98op] => Array
(
[p5ld2se] => Array
(
[0] => 1
[1] => 4
[2] => 217
[3] => 432
)
[38hjp9] => Array
(
[2we8t2] => Array
(
[0] => 1
[1] => 4
[2] => 217
[3] => 432
)
[1142ln] => Array
(
[0] => 1
[1] => 4
[2] => 217
[3] => 432
)
)
[669yo36] => Array
(
[6318u7] => Array
(
[22rv86] => Array
(
[0] => 1
[1] => 4
[2] => 217
[3] => 432
)
[13we42] => Array
(
[0] => 1
[1] => 4
[2] => 217
[3] => 432
)
)
[jk66d3] => Array
(
[0] => 1
[1] => 4
[2] => 217
[3] => 432
)
)
)
)
Answer the question
In order to leave comments, you need to log in
1. If you want to change an element in the array, then you need to specify a reference to it &$val
2. When you run recursion and you need the data that it returns, then you need to write it down $val = deep($val);
3. You can’t foreach
use it array_merge
Here’s what happened:
$test_mass = [
'tk98op' => [
'p5ld2se' => [],
'38hjp9' => [
'2we8t2' => [],
'1142ln' => [],
],
'669yo36' => [
'6318u7' => [
'22rv86' => [],
'13we42' => [],
],
'jk66d3' => [],
],
],
];
function deep($mass)
{
foreach ($mass as $key => &$val) {
$val = (\is_array($val) && \count($val) === 0)
?
[1, 4, 217, 432]
: deep($val);
}
unset($val);
return $mass;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question