array values recursive php

array_walk_recursive

array_walk_recursive — Рекурсивно применяет пользовательскую функцию к каждому элементу массива

Описание

Список параметров

Если требуется, чтобы функция callback изменила значения в массиве, определите первый параметр callback как ссылку. Тогда все изменения будут применены к элементам массива.

Возвращаемые значения

Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.

Примеры

Пример #1 Пример использования array_walk_recursive()

Результат выполнения данного примера:

Смотрите также

User Contributed Notes 27 notes

Since this is only mentioned in the footnote of the output of one of the examples, I feel it should be spelled out:

* THIS FUNCTION ONLY VISITS LEAF NODES *

That is to say that if you have a tree of arrays with subarrays of subarrays, only the plain values at the leaves of the tree will be visited by the callback function. The callback function isn’t ever called for a nodes in the tree that subnodes (i.e., a subarray). This has the effect as to make this function unusable for most practical situations.

How to modify external variable from inside recursive function using userdata argument.

// result
// 11 : 1
// 12 : 1
// 2 : 1
// counter: 0

// result
// 11 : 1
// 12 : 2
// 2 : 1
// counter : 0

// result
// 11 : 1
// 12 : 2
// 2 : 3
// counter : 3

Unfortunately the PHP example given doesn’t do this. It actually took me a while to figure out why my function wasn’t changing the original array, even though I was passing by reference.

One other silly thing you might try first is something like this:

I use RecursiveIteratorIterator with parameter CATCH_GET_CHILD to iterate on leafs AND nodes instead of array_walk_recursive function :

The description says «If funcname needs to be working with the actual values of the array, specify the first parameter of funcname as a reference.» This isn’t necessarily helpful as the function you’re calling might be built in (e.g. trim or strip_tags). One option would be to create a version of these like so.

multidimensional array to single array

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

array_walk_recursive itself cannot unset values. Even though you can pass array by reference, unsetting the value in the callback will only unset the variable in that scope.

A simple solution for walking a nested array to obtain the last set value of a specified key:

I needed to add or modify values in an array with unknown structure. I was hoping to use array_walk_recursive for the task, but because I was also adding new nodes I came up with an alternate solution.

I decided to add to the previous PHP 4 compatible version of array_walk_recursive() so that it would work within a class and as a standalone function. Both instances are handled by the following function which I modified from omega13a at sbcglobal dot net.

The following example is for usage within a class. To use as a standalone function take it out of the class and rename it. (Example: array_walk_recursive_2)

Источник

array_replace_recursive

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

array_replace_recursive — Replaces elements from passed arrays into the first array recursively

Description

array_replace_recursive() replaces the values of array with the same values from all the following arrays. If a key from the first array exists in the second array, its value will be replaced by the value from the second array. If the key exists in the second array, and not the first, it will be created in the first array. If a key only exists in the first array, it will be left as is. If several arrays are passed for replacement, they will be processed in order, the later array overwriting the previous values.

array_replace_recursive() is recursive : it will recurse into arrays and apply the same process to the inner value.

When the value in the first array is scalar, it will be replaced by the value in the second array, may it be scalar or array. When the value in the first array and the second array are both arrays, array_replace_recursive() will replace their respective value recursively.

Parameters

The array in which elements are replaced.

Arrays from which elements will be extracted.

Return Values

Examples

Example #1 array_replace_recursive() example

The above example will output:

Example #2 array_replace_recursive() and recursive behavior

The above example will output:

See Also

User Contributed Notes 7 notes

(I suppose it treats it as just another recursive level to dive in, finding no key to compare, backtracking while leaving this sub-tree alone)

$result is still: [‘first’ => [‘second’ => ‘hello’]].

Nice that this function finally found its was to the PHP core! If you want to use it also with older PHP versions before 5.3.0, you can define it this way:

If you implemented such a compatible function before and don’t want to refactor all your code, you can update it with the following snippet to use the native (and hopefully faster) implementation of PHP 5.3.0, if available. Just start your function with these lines:

Источник

array_values

(PHP 4, PHP 5, PHP 7, PHP 8)

array_values — Выбирает все значения массива

Описание

Список параметров

Возвращаемые значения

Возвращает индексированный массив значений.

Примеры

Пример #1 Пример использования array_values()

Результат выполнения данного примера:

Смотрите также

User Contributed Notes 25 notes

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

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

Doing this will cause PHP exceeds the momory limits:

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

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:

I needed a function that recursively went into each level of the array to order (only the indexed) arrays. and NOT flatten the whole thing.

Remember, that the following way of fetching data from a mySql-Table will do exactly the thing as carl described before: An array, which data may be accessed both by numerical and DB-ID-based Indexes:

/*
fruit1 = apple
fruit2 = orange
fruit5 = apple
*/
?>

A comment on array_merge mentioned that array_splice is faster than array_merge for inserting values. This may be the case, but if your goal is instead to reindex a numeric array, array_values() is the function of choice. Performing the following functions in a 100,000-iteration loop gave me the following times: ($b is a 3-element array)

array_splice($b, count($b)) => 0.410652
$b = array_splice($b, 0) => 0.272513
array_splice($b, 3) => 0.26529
$b = array_merge($b) => 0.233582
$b = array_values($b) => 0.151298

same array_flatten function, compressed and preserving keys.

/**********************************************
*
* PURPOSE: Flatten a deep multidimensional array into a list of its
* scalar values
*
* array array_values_recursive (array array)
*
* WARNING: Array keys will be lost
*
*********************************************/

Non-recursive simplest array_flatten.

A modification of wellandpower at hotmail.com’s function to perform array_values recursively. This version will only re-index numeric keys, leaving associative array indexes alone.

Please note that ‘wellandpower at hotmail.com’s recursive merge doesn’t work. Here’s the fixed version:

The function here flatterns an entire array and was not the behaviour I expected from a function of this name.

I expected the function to flattern every sub array so that all the values were aligned and it would return an array with the same dimensions as the imput array, but as per array_values() adjusting the keys rater than removing them.

In order to do this, you will want this function:

function array_values_recursive($array) <
$temp = array();

Hopefully this will assist.

Note that in a multidimensional array, each element may be identified by a _sequence_ of keys, i.e. the keys that lead towards that element. Thus «preserving keys» may have different interpretations. Ivan’s function for example creates a two-dimensional array preserving the last two keys. Other functions below create a one-dimensional array preserving the last key. For completeness, I will add a function that merges the key sequence by a given separator and a function that preserves the last n keys, where n is arbitrary.

/*
* Flattening a multi-dimensional array into a
* single-dimensional one. The resulting keys are a
* string-separated list of the original keys:
*
* a[x][y][z] becomes a[implode(sep, array(x,y,z))]
*/

Источник

Search for a key in an array, recursively

Hey, this method searches for a specific key in an associative array and returns the value associated with it. There’s some problem with the recursion. Any clue?

array values recursive php

7 Answers 7

Maybe it’s overkill, but it’s funny to use RecursiveIterators 🙂

UPDATE: Maybe it was overkill with old versions of PHP, but with >=5.6 (specially with 7.0) I would totally use this without doubt.

UPDATE: Also, as of PHP 5.6, with generators you can easily iterate over all elements which pass the filter, not only the first one:

you need to stop the recursive deep search, by return false and then check it in the function.

you can find more examples of functions (like using RecursiveArrayIterator and more) in this link : http://php.net/manual/en/function.array-search.php

The answer provided by xPheRe was extremely helpful, but didn’t quite solve the problem in my implementation. There are multiple nested associative arrays in our data structure, and there may be multiple occurrences of any given key.

In order to suit our purposes, I needed to implement a holder array that was updated while traversing the entire structure, instead of returning on the first match. The real work was provided by another poster, but I wanted to say thanks and share the final step that I had to cover.

The best solution above misses the case if the key is repeated and only returns the first value, here I get all the values in an array instead:

I just been through a similar issue and here’s what worked for me:

This is going to return an array containing the value of all the matching keys it found in the multidimensional array. I tested this with arrays dinamically generated by an e-mail API. In the case of multiple matches, you just need to create a simple foreach loop to sort the array however you want.

I noticed the main mistake I was making was using if-ifelse conditions when I should be using if-if conditions. Any questions or criticism are very welcome, cheers!

array values recursive php

I recently came across the same issue, when dealing with Yii2 query object.

The reason your function didn’t work is that the return action doesn’t work here. Just pass a reference parameter to store the value, and do whatever you want afterwards.

As you can see, this is a simple PHP function doesn’t rely on any library. So I think its worth to mention with all the answer listed above.

array values recursive php

Linked

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.16.40224

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

I need an array_keys_recursive()

I tried using that function but it still only returns the first key.

array values recursive php

8 Answers 8

Using SPL, looping over the keys is quite easy (store them in another array if you wish):

I see a lot of overly complicated solutions here.

array values recursive php

The main problem is that you are throwing away the results of the recursive show_keys() calls. You don’t do anything with the return value.

Comments are inline.

This might do the trick?

As a supplement for other solutions there is possibility to return flattened array as a result but still keep the information about the tree. We can concatenate nested keys with parent. It could be useful for diffing with other arrays as you are distinguishing between same child keys but different parents

The question is ambiguous because you did not specify your input and expected output.

Consider this example array:

All of the other solutions so far provide a flattened one-dimensional array list of keys.

However, I had a need for an array_keys_recursive function that would preserve the hierarchy.

For anyone else searching for a similar need, here’s my solution:

array values recursive php

Ofcause this function is infinite. But my task is to help you)

array values recursive php

at the start of the function.

Note that using global variables is not good programming. You need to pass your array as argument to your recursive calls and modify the passed array by adding keys found in each iterations as Alexander and John have done.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *