Array values recursive php

array_values in PHP Multidimensional Array | 3 Code Examples

If you want to use the array_values function with a multidimensional PHP array, the best approach is to create a recursive function that loops through the levels to call itself and iterate deeper. This allows you to have unlimited array depth.

Using PHP array_values in a multidimensional array

The array_values function retrieves the values from an associative array in PHP.

It takes an array as an argument and returns an array including the values. The usage is straightforward for a linear associative array. However, things get complicated when PHP multidimensional array factors in.

A multidimensional array can include numbers and levels of nested arrays, and a hard-coded approach does not go well with complexities.

That’s why we seek a more generalized algorithm to use PHP array_values in a multidimensional array, and that’s precisely what this array intends to show you.

So, before we come to the main course, let’s quickly review the PHP array_values function.

PHP array_values – A review

Here’s the function signature of the array_values.

array_values(array $array): array

The function receives an array and returns the retrieved values in an array. An example is as follows.

PHP array_values Code Example

 "Bob", "Employee#2" => "Stacie", "Employee#3" => "Robert", "Employee#4" => "Anna", "Employee#5" => "Matthew", "Employee#6" => "John" ); print_r(array_values($employees_array)); /* OUTPUT Array ( [0] => Bob [1] => Stacie [2] => Robert [3] => Anna [4] => Matthew [5] => John ) */ ?> 

The array_values returns a numerical index array of the employee array’s values.

The array was linear, and a call to the function worked great. But what if we have a multidimensional array?

That’s what we are here for today.

Use PHP array_values recursively

As mentioned, a PHP multidimensional array can include any number or level of nested arrays. So, an algorithm should be generalized enough not to care about the structure of an associative array in PHP.

Recursion is the way out here.

A recursive algorithm can dig deep into any multidimensional array and return a linear array of values.

So, let’s take a look at this recursive array_values algorithm.

PHP Recursive Function Code Example

function array_values_recursive($arr) < $result = array(); foreach( array_keys($arr) as $k )< $v = $arr[$k]; if (is_scalar($v)) < $result[] = $v; >elseif (is_array($v)) < $result = array_merge( $result, array_values_recursive($v)); >> return $result; > 

So, the function makes recursive calls if it finds an array and merges it into the result array to form a linear array.

Читайте также:  Home

Let’s try to run this function over some different PHP multidimensional arrays.

Test#1 – Two dimensional PHP associative array

Here’s a two-dimensional array in PHP.

$arr = [ ['a','b'], ['c', 'd'], ['e', 'f'], ['g', 'h'], ['i', 'j'], ['k', 'l'], ['m', 'n'], ['o', 'p'], ['q', 'r'], ['s', 't'], ['u', 'v'], ['w', 'x'], ['y', 'z'] ]; 

Here’s the output after recursive PHP array_values.

Array ( [0] => a [1] => b [2] => c [3] => d [4] => e [5] => f [6] => g [7] => h [8] => i [9] => j [10] => k [11] => l [12] => m [13] => n [14] => o [15] => p [16] => q [17] => r [18] => s [19] => t [20] => u [21] => v [22] => w [23] => x [24] => y [25] => z ) 

Test#2 – Three dimensional PHP associative array

Here’s a three-dimensional array in PHP.

$arr = [ ['1', ['2']], ['3', ['4']], ['5', ['6']], ['7', ['8']], ['9', ['10']] ]; 

Here’s the output with array_values recursive.

Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9 [9] => 10 ) 

Test#3 – Four dimensional PHP array_values

Here’s a four-dimensional array in PHP.

$arr = [ ['A', ['B', ['C']]], ['D', ['E', ['F']]], ['G', ['H', ['I']]], ['J', ['K', ['L']]], ['M', ['N', ['O']]], ['P', ['Q', ['R']]], ['S', ['T', ['U']]], ['V', ['W',['X']]], ['Y', 'Z'] ]; 

So, here’s the output with array_values recursive.

Array ( [0] => A [1] => B [2] => C [3] => D [4] => E [5] => F [6] => G [7] => H [8] => I [9] => J [10] => K [11] => L [12] => M [13] => N [14] => O [15] => P [16] => Q [17] => R [18] => S [19] => T [20] => U [21] => V [22] => W [23] => X [24] => Y [25] => Z ) 

Voila! Three test cases passed. So, that’s convincing enough that the function generalizes well for PHP multidimensional arrays.

Conclusion

This article focuses on using array_values in a multidimensional array.

First, the article overviews the array_values function and discusses the challenges with the PHP multidimensional array. Then, it introduces a recursive algorithm and tests some multidimensional arrays.

These tests pass, and the algorithm generalizes well for PHP multidimensional arrays.

Hopefully, this article has been of some value to you. You can start learning PHP by following the articles and tutorials at FuelingPHP.

Want to learn more about PHP?

We have many fun articles related to PHP. You can explore these to learn more about PHP.

Источник

array_values

array_values() returns all the values from the array and indexes the array numerically.

Parameters

Return Values

Returns an indexed array of values.

Examples

Example #1 array_values() example

The above example will output:

Читайте также:  Python socket client пример

See Also

  • array_keys() — Return all the keys or a subset of the keys of an array
  • array_combine() — Creates an array by using one array for keys and another for its values

User Contributed Notes 6 notes

Remember, array_values() will ignore your beautiful numeric indexes, it will renumber them according tho the ‘foreach’ ordering:

print_r ( array_values ( $a ));
==>
Array(
[ 0 ] => 11
[ 1 ] => 22
[ 2 ] => 33
[ 3 ] => 44
)
?>

Just a warning that re-indexing an array by array_values() may cause you to reach the memory limit unexpectly.

For example, if your PHP momory_limits is 8MB,
and says there’s a BIG array $bigArray which allocate 5MB of memory.

Doing this will cause PHP exceeds the momory limits:

$bigArray = array_values ( $bigArray );
?>

It’s because array_values() does not re-index $bigArray directly,
it just re-index it into another array, and assign to itself later.

This is another way to get value from a multidimensional array, but for versions of php >= 5.3.x
/**
* Get all values from specific key in a multidimensional array
*
* @param $key string
* @param $arr array
* @return null|string|array
*/
function array_value_recursive ( $key , array $arr ) $val = array();
array_walk_recursive ( $arr , function( $v , $k ) use( $key , & $val ) if( $k == $key ) array_push ( $val , $v );
>);
return count ( $val ) > 1 ? $val : array_pop ( $val );
>

$arr = array(
‘foo’ => ‘foo’ ,
‘bar’ => array(
‘baz’ => ‘baz’ ,
‘candy’ => ‘candy’ ,
‘vegetable’ => array(
‘carrot’ => ‘carrot’ ,
)
),
‘vegetable’ => array(
‘carrot’ => ‘carrot2’ ,
),
‘fruits’ => ‘fruits’ ,
);

var_dump ( array_value_recursive ( ‘carrot’ , $arr )); // array(2) < [0]=>string(6) «carrot» [1]=> string(7) «carrot2» >
var_dump ( array_value_recursive ( ‘apple’ , $arr )); // null
var_dump ( array_value_recursive ( ‘baz’ , $arr )); // string(3) «baz»
var_dump ( array_value_recursive ( ‘candy’ , $arr )); // string(5) «candy»
var_dump ( array_value_recursive ( ‘pear’ , $arr )); // null
?>

Most of the array_flatten functions don’t allow preservation of keys. Mine allows preserve, don’t preserve, and preserve only strings (default).

// recursively reduces deep arrays to single-dimensional arrays
// $preserve_keys: (0=>never, 1=>strings, 2=>always)
function array_flatten($array, $preserve_keys = 1, &$newArray = Array()) foreach ($array as $key => $child) if (is_array($child)) $newArray =& array_flatten($child, $preserve_keys, $newArray);
> elseif ($preserve_keys + is_string($key) > 1) $newArray[$key] = $child;
> else $newArray[] = $child;
>
>
return $newArray;
>

echo ‘var_dump($array);’.»\n»;
var_dump($array);
echo ‘var_dump(array_flatten($array, 0));’.»\n»;
var_dump(array_flatten($array, 0));
echo ‘var_dump(array_flatten($array, 1));’.»\n»;
var_dump(array_flatten($array, 1));
echo ‘var_dump(array_flatten($array, 2));’.»\n»;
var_dump(array_flatten($array, 2));
?>

If you are looking for a way to count the total number of times a specific value appears in array, use this function:

function array_value_count ( $match , $array )
<
$count = 0 ;

foreach ( $array as $key => $value )
<
if ( $value == $match )
<
$count ++;
>
>

return $count ;
>
?>

This should really be a native function of PHP.

/**
flatten an arbitrarily deep multidimensional array
into a list of its scalar values
(may be inefficient for large structures)
(will infinite recurse on self-referential structures)
(could be extended to handle objects)
*/
function array_values_recursive ( $ary )
$lst = array();
foreach( array_keys ( $ary ) as $k ) $v = $ary [ $k ];
if ( is_scalar ( $v )) $lst [] = $v ;
> elseif ( is_array ( $v )) $lst = array_merge ( $lst ,
array_values_recursive ( $v )
);
>
>
return $lst ;
>
?>

Читайте также:  Python base64 decode to utf 8

code till dawn! -mark meves!

  • Array Functions
    • array_​change_​key_​case
    • array_​chunk
    • array_​column
    • array_​combine
    • array_​count_​values
    • array_​diff_​assoc
    • array_​diff_​key
    • array_​diff_​uassoc
    • array_​diff_​ukey
    • array_​diff
    • array_​fill_​keys
    • array_​fill
    • array_​filter
    • array_​flip
    • array_​intersect_​assoc
    • array_​intersect_​key
    • array_​intersect_​uassoc
    • array_​intersect_​ukey
    • array_​intersect
    • array_​is_​list
    • array_​key_​exists
    • array_​key_​first
    • array_​key_​last
    • array_​keys
    • array_​map
    • array_​merge_​recursive
    • array_​merge
    • array_​multisort
    • array_​pad
    • array_​pop
    • array_​product
    • array_​push
    • array_​rand
    • array_​reduce
    • array_​replace_​recursive
    • array_​replace
    • array_​reverse
    • array_​search
    • array_​shift
    • array_​slice
    • array_​splice
    • array_​sum
    • array_​udiff_​assoc
    • array_​udiff_​uassoc
    • array_​udiff
    • array_​uintersect_​assoc
    • array_​uintersect_​uassoc
    • array_​uintersect
    • array_​unique
    • array_​unshift
    • array_​values
    • array_​walk_​recursive
    • array_​walk
    • array
    • arsort
    • asort
    • compact
    • count
    • current
    • end
    • extract
    • in_​array
    • key_​exists
    • key
    • krsort
    • ksort
    • list
    • natcasesort
    • natsort
    • next
    • pos
    • prev
    • range
    • reset
    • rsort
    • shuffle
    • sizeof
    • sort
    • uasort
    • uksort
    • usort
    • each

    Источник

    Как сделать рекурсивный обход массива php

    Для этого можно использовать встроенную функцию array_walk_recursive(). Первым параметром она принимает массив, а вторым колбек, который будет выполнен на каждом элементе массива. Колбек же, в свою очередь, принимает два параметра: элемент и его ключ. Ниже небольшой пример с распечаткой элементов вложенного массива на экран.

     $collection = [ 'root' => [ 'key1' => 'value1', 'key2' => 'value2', 'key3' => [ 'key4' => 'value4' ] ] ]; array_walk_recursive($collection, function ($value, $key)  var_dump("$key> -> $value>"); >); // => string(14) "key1 -> value1" // => string(14) "key2 -> value2" // => string(14) "key4 -> value4" 

    Стоит сказать, что если значение ключа содержит массив, то этот ключ не передаётся в колбек. Потому мы и не видим в выводе ключей root и key3 .

    Источник

    Перебор и замена данных в многомерном массиве?

    Добрый день. Подскажите пожалуйста как можно более изящно (при этом не снижая производительность) сделать следующее.

    $a = [ 1 => [ 3 => [ "logo" => "logo_3_1", "cover" => "cover_3_1" ], 4 => [ "logo" => "logo_4_1", ] ], 2 => [ 5 => [ "logo" => "logo_5_2", "cover" => "cover_5_2" ] ] ];

    В нем хранятся определенные сущности, у которых есть идентификаторы (logo_3_1, cover_3_1 и т.д).

    Задача.
    Нужно пройтись по этому массиву и выбрать эти идентификаторы. Потому на основании их будет сделана выборка и мы получим пути к изображениям.

    Сейчас это реализована через foreach вложенный в foreach и т.д. Что для выборки идентификаторов что для замены их на пути.

    Попробовал использовать итераторы

    $r = []; $ai = new RecursiveArrayIterator($a); $ari = new RecursiveIteratorIterator($ai); foreach ($ari as $key => $value)

    В результате в $r у нас есть все идентификаторы.

    А вот тоже самое провернуть с обновлением исходного массива не получается. Т.е так же самая конструкция не позволяет нам обновить значение.

    function simpleIterator($iterator, $result) < while ($iterator->valid()) < if ($iterator->hasChildren()) < simpleIterator($iterator->getChildren(), $result); > else < if ($result[$iterator->current()]) < $iterator->offsetSet($iterator->key(), $result[$iterator->current()]); >; > $iterator->next(); > >; iterator_apply($ai, 'simpleIterator', [$ai, $images]);

    Подскажите пожалуйста, что я делаю не так, возможно выбранный подход тупиковый.

    Источник

Оцените статью