применить функцию к каждому элементу массива 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)

Источник

Функции для работы с массивами

Содержание

User Contributed Notes 14 notes

A simple trick that can help you to guess what diff/intersect or sort function does by name.

Example: array_diff_assoc, array_intersect_assoc.

Example: array_diff_key, array_intersect_key.

Example: array_diff, array_intersect.

Example: array_udiff_uassoc, array_uintersect_assoc.

This also works with array sort functions:

Example: arsort, asort.

Example: uksort, ksort.

Example: rsort, krsort.

Example: usort, uasort.

?>
Return:
Array ( [ 0 ] => Cero [ 1 ] => Uno [ 2 ] => Dos [ 3 ] => Cuatro [ 4 ] => Cinco [ 5 ] => Tres [ 6 ] => Seis [ 7 ] => Siete [ 8 ] => Ocho [ 9 ] => Nueve [ 10 ] => Diez )
Array ( [ 0 ] => Cero [ 1 ] => Uno [ 2 ] => Dos [ 3 ] => Tres [ 4 ] => Cuatro [ 5 ] => Cinco [ 6 ] => Seis [ 7 ] => Siete [ 8 ] => Ocho [ 9 ] => Nueve [ 10 ] => Diez )
?>

Updated code of ‘indioeuropeo’ with option to input string-based keys.

Here is a function to find out the maximum depth of a multidimensional array.

// return depth of given array
// if Array is a string ArrayDepth() will return 0
// usage: int ArrayDepth(array Array)

Short function for making a recursive array copy while cloning objects on the way.

If you need to flattern two-dismensional array with single values assoc subarrays, you could use this function:

to 2g4wx3:
i think better way for this is using JSON, if you have such module in your PHP. See json.org.

to convert JS array to JSON string: arr.toJSONString();
to convert JSON string to PHP array: json_decode($jsonString);

You can also stringify objects, numbers, etc.

Function to pretty print arrays and objects. Detects object recursion and allows setting a maximum depth. Based on arraytostring and u_print_r from the print_r function notes. Should be called like so:

I was looking for an array aggregation function here and ended up writing this one.

Note: This implementation assumes that none of the fields you’re aggregating on contain The ‘@’ symbol.

While PHP has well over three-score array functions, array_rotate is strangely missing as of PHP 5.3. Searching online offered several solutions, but the ones I found have defects such as inefficiently looping through the array or ignoring keys.

Источник

array_walk

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

Описание

Применяет пользовательскую функцию funcname к каждому элементу массива array.

array_walk() не подвержена влиянию внутреннего указателя массива array. array_walk() обойдёт все элементы массива независимо от позиции указателя.

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

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

Множество встроенных функций (например, strtolower() ) выводят предупреждение, если им передано больше параметров, чем они ожидают, или которые не могут непосредственно использоваться в funcname.

Потенциально изменены могут быть только значения массива array; структура самого массива не может быть изменена, то есть нельзя добавить, удалить или поменять порядок элементов. Если callback-функция не соответствует этому требованию, поведение данной функции станет неопределённым и непредсказуемым.

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

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

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

Ошибки

Примеры

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

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

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

Источник

Массивы

User Contributed Notes 17 notes

For newbies like me.

Creating new arrays:-
//Creates a blank array.
$theVariable = array();

//Creates an array with elements.
$theVariable = array(«A», «B», «C»);

//Creating Associaive array.
$theVariable = array(1 => «http//google.com», 2=> «http://yahoo.com»);

//Creating Associaive array with named keys
$theVariable = array(«google» => «http//google.com», «yahoo»=> «http://yahoo.com»);

Note:
New value can be added to the array as shown below.
$theVariable[] = «D»;
$theVariable[] = «E»;

To delete an individual array element use the unset function

output:
Array ( [0] => fileno [1] => Array ( [0] => uid [1] => uname ) [2] => topingid [3] => Array ( [0] => touid [1] => Array ( [0] => 1 [1] => 2 [2] => Array ( [0] => 3 [1] => 4 ) ) [2] => touname ) )

when I hope a function string2array($str), «spam2» suggest this. and It works well

hope this helps us, and add to the Array function list

Another way to create a multidimensional array that looks a lot cleaner is to use json_decode. (Note that this probably adds a touch of overhead, but it sure does look nicer.) You can of course add as many levels and as much formatting as you’d like to the string you then decode. Don’t forget that json requires » around values, not ‘!! (So, you can’t enclose the json string with » and use ‘ inside the string.)

Converting a linear array (like a mysql record set) into a tree, or multi-dimensional array can be a real bugbear. Capitalizing on references in PHP, we can ‘stack’ an array in one pass, using one loop, like this:

$node [ ‘leaf’ ][ 1 ][ ‘title’ ] = ‘I am node one.’ ;
$node [ ‘leaf’ ][ 2 ][ ‘title’ ] = ‘I am node two.’ ;
$node [ ‘leaf’ ][ 3 ][ ‘title’ ] = ‘I am node three.’ ;
$node [ ‘leaf’ ][ 4 ][ ‘title’ ] = ‘I am node four.’ ;
$node [ ‘leaf’ ][ 5 ][ ‘title’ ] = ‘I am node five.’ ;

Hope you find it useful. Huge thanks to Nate Weiner of IdeaShower.com for providing the original function I built on.

If an array item is declared with key as NULL, array key will automatically be converted to empty string », as follows:

A small correction to Endel Dreyer’s PHP array to javascript array function. I just changed it to show keys correctly:

function array2js($array,$show_keys)
<
$dimensoes = array();
$valores = array();

Made this function to delete elements in an array;

?>

but then i saw the methods of doing the same by Tyler Bannister & Paul, could see that theirs were faster, but had floors regarding deleting multiple elements thus support of several ways of giving parameters. I combined the two methods to this to this:

?>

Fast, compliant and functional 😉

//Creating a multidimensional array

/* 2. Works ini PHP >= 5.4.0 */

var_dump ( foo ()[ ‘name’ ]);

/*
When i run second method on PHP 5.3.8 i will be show error message «PHP Fatal error: Can’t use method return value in write context»

array_mask($_REQUEST, array(‘name’, ’email’));

Источник

array_walk

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

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

Описание

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

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

Потенциально изменены могут быть только значения массива array ; структура самого массива не может быть изменена, то есть нельзя добавить, удалить или поменять порядок элементов. Если callback-функция не соответствует этому требованию, поведение данной функции станет неопределённым и непредсказуемым.

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

Возвращает true

Ошибки

Примеры

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

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

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

User Contributed Notes 34 notes

PHP ignored arguments type when using array_walk() even if there was

declare( strict_types = 1 );

butter: 5
meat: 7
banana: 3

whilst the expecting output is :

Fatal error: Uncaught TypeError: Argument 1 passed to test_print() must be of the type integer

because «butter» => 5.3 is float

I asked someone about it and they said «this was caused by the fact that callbacks called from internal code will always use weak type». But I tried to do some tests and this behavior is not an issue when using call_user_func().

Calling an array Walk inside a class

If the class is static:
array_walk($array, array(‘self’, ‘walkFunction’));
or
array_walk($array, array(‘className’, ‘walkFunction’));

Otherwise:
array_walk($array, array($this, ‘walkFunction’));

There is a note about 3 years ago regarding using this for trimming. array_map() may be cleaner for this. I haven’t checked the time/resource impact:

Correction for the speed test from zlobnygrif.

// Test results
$array1 = test ( ‘array_walk’ );
$array2 = test ( ‘array_walk_list_each’ );
$array3 = test ( ‘array_walk_foreach1’ );
$array4 = test ( ‘array_walk_foreach2’ );

In response to ‘ibolmo’, this is an extended version of string_walk, allowing to pass userdata (like array_walk) and to have the function edit the string in the same manner as array_walk allows, note now though that you have to pass a variable, since PHP cannot pass string literals by reference (logically).

// We can make that with this simple FOREACH loop :

$fruits = array(«d» => «lemon», «a» => «orange», «b» => «banana», «c» => «apple»);

Array
(
[d] => fruit: lemon
[a] => fruit: orange
[b] => fruit: banana
[c] => fruit: apple
)

For those that think they can’t use array_walk to change / replace a key name, here you go:

I wanted to walk an array and reverse map it into a second array. I decided to use array_walk because it should be faster than a reset,next loop or foreach(x as &$y) loop.

Don’t forget about the array_map() function, it may be easier to use!

Here’s how to lower-case all elements in an array:

It can be very useful to pass the third (optional) parameter by reference while modifying it permanently in callback function. This will cause passing modified parameter to next iteration of array_walk(). The exaple below enumerates items in the array:

Array
(
[0] => 1 lemon
[1] => 2 orange
[2] => 3 banana
[3] => 4 apple
)
$num is: 1

As a conclusion, using references with array_walk() can be powerful toy but this should be done carefully since modifying third parameter outside the array_walk() is not always what we want.

array_walk does not work on SplFixedArray objects:
= new SplFixedArray ( 2 );
$array [ 0 ] = ‘test_1’ ;
$array [ 1 ] = ‘test_2’ ;

Unfortunately I spent a lot of time trying to permanently apply the effects of a function to an array using the array_walk function when instead array_map was what I wanted. Here is a very simple though effective example for those who may be getting overly frustrated with this function.

Prefix array values with keys and retrieve as a glued string, the original array remains unchanged. I used this to create some SQL queries from arrays.

Using lambdas you can create a handy zip function to zip together the keys and values of an array. I extended it to allow you to pass in the «glue» string as the optional userdata parameter. The following example is used to zip an array of email headers:

/*
From: Matthew Purdon
Reply-To: Matthew Purdon
Return-path:
X-Mailer: PHP5.3.2
Content-Type: text/plain; charset=»UTF-8″
*/
?>

// Test results
$array1 = test ( ‘array_walk’ );
$array2 = test ( ‘array_walk_list_each’ );
$array3 = test ( ‘array_walk_foreach1’ );
$array4 = test ( ‘array_walk_foreach2’ );

PHP 5.5 array_walk looks pretty good but list each is more and more quickly.

For completeness one has to mention the possibility of using this function with PHP 5.3 closures:

You can use lambda function as a second parameter:

I was looking for trimming all the elements in an array, I found this as the simplest solution:

And to set allow_call_time_pass_reference to true in php.ini won’t work, according to http://bugs.php.net/bug.php?id=19699 thus to work around:

example with closures, checking and deleting value in array:

You can change the key or value with array_walk if you use the temporal returned array in global inside the function. For example:

$array = [‘a’=>10, ‘b’=>20];
$sequence = array ();

$newArray = array_values(array_walk($array, ‘fn’));

No need to concern about the place of the internal pointer for the baby array. You have now rewinded, 0 based new array, string key one instead.

If you want to add values with same key from two arrays :

echo «» ;
?>

This will output:

«orange» => 3,
«banana» => 3,
«apple» => 5

here is a simple and yet easy to use implementation of this function.
the ‘original’ function has the problem that you can’t unset a value.
with my function, YOU CAN!

limitations: it only can run user defined functions.
i hope you like it!

You want to get rid of the whitespaces users add in your form fields.
Simply use.

so.
$obj = new SomeVeryImportantClass;
$obj->mungeFormData($_POST);
___
eNc

For all those people trying to shoe-horn trim() into array_walk() and have found all these tricks to work around the issue with array_walk() passing 2 parameters to the callback.

Check out array_map().

It’s all sorts of win.

For the record. I’m one of these people and after 15 years of php development I’m pleased to say that there’s still things I’m learning. 🙂 I just found out about array_map() myself.

return true ; // success!
> // arrayWalk()

So, still some work left.

Beware that «array ($this, method)» construct. If you’re wanting to alter members of the «$this» object inside «method» you should construct the callback like this:

if you want to modify every value of an multidimensional array use this function used here:

Array ( [ 1 ] => 1test [ 2 ] => 2test [ 3 ] => Array ( [ 1 ] => 11test [ 2 ] => 12test [ 3 ] => 13test ) )
?>

Источник

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

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