php array filter by keys
PHP: Как использовать array_filter() для фильтрации ключей массива?
Функция обратного вызова в array_filter() передает только значения массива, а не ключи.
ОТВЕТЫ
Ответ 1
Ответ 2
Ответ 3
Мне нужно было сделать то же самое, но с более сложным array_filter на клавишах.
Вот как я это сделал, используя аналогичный метод.
Это выводит результат:
Ответ 4
Вот более гибкое решение, использующее закрытие:
Таким образом, в функции вы можете выполнять другие специальные тесты.
Ответ 5
Если вы ищете метод фильтрации массива по строке, входящей в ключи, вы можете использовать:
Результат print_r($mResult) равен
Адаптация этого ответа, который поддерживает регулярные выражения
Ответ 6
Как получить текущий ключ массива при использовании array_filter
Он передает массив, который вы фильтруете, в качестве ссылки на обратный вызов. Поскольку array_filter не традиционно перебирает массив, увеличивая его внутренний внутренний указатель, вы должны заранее его продвигать.
Важно то, что вам нужно убедиться, что ваш массив reset, иначе вы можете начать прямо посередине.
В PHP >= 5.4 вы можете сделать обратный вызов еще короче:
Ответ 7
Здесь менее гибкая альтернатива, использующая unset():
Это неприменимо, если вы хотите сохранить отфильтрованные значения для последующего использования, но более аккуратные, если вы уверены, что этого не делаете.
Ответ 8
Начиная с PHP 5.6, вы можете использовать флаг ARRAY_FILTER_USE_KEY в array_filter :
В противном случае вы можете использовать эту функцию (из TestDummy):
И вот расширенная версия моей, которая принимает обратный вызов или непосредственно ключи:
И последнее, но не менее важное: вы также можете использовать простой foreach :
Ответ 9
Возможно, излишний, если вам это нужно, только один раз, но вы можете использовать YaLinqo library * для фильтрации коллекций (и выполнять любые другие преобразования). Эта библиотека позволяет формировать SQL-подобные запросы на объектах с плавным синтаксисом. Функция where принимает возврат с двумя аргументами: значением и ключом. Например:
Ответ 10
Функция фильтра массива из php:
Пример: Рассмотрим простой массив
Если вы хотите фильтровать массив на основе ключа массива, нам нужно использовать ARRAY_FILTER_USE_KEY как третий параметр функции массива array_filter.
Если вы хотите фильтровать массив на основе ключа массива и значения массива, нам нужно использовать ARRAY_FILTER_USE_BOTH как третий параметр функции массива array_filter.
Примеры функций обратного вызова:
Ответ 11
С помощью этой функции вы можете фильтровать многомерный массив
Ответ 12
Ответ 13
функция для удаления некоторых элементов массива
Array ( [0] => first ) результата Array ( [0] => first )
array_filter
(PHP 4 >= 4.0.6, PHP 5, PHP 7)
array_filter — Фильтрует элементы массива с помощью callback-функции
Описание
Список параметров
Возвращаемые значения
Возвращает отфильтрованный массив.
Список изменений
Версия | Описание |
---|---|
5.6.0 | Добавлен необязательный параметр flag и константы ARRAY_FILTER_USE_KEY и ARRAY_FILTER_USE_BOTH |
Примеры
Пример #1 Пример использования array_filter()
Результат выполнения данного примера:
Результат выполнения данного примера:
Пример #3 array_filter() с указанным flag
Результат выполнения данного примера:
Примечания
Если callback-функция изменяет массив (например, добавляет или удаляет элементы), поведение этой функции неопределено.
Смотрите также
User Contributed Notes 44 notes
In case you are interested (like me) in filtering out elements with certain key-names, array_filter won’t help you. Instead you can use the following:
Here is how you could easily delete a specific value from an array with array_filter:
array_filter remove also FALSE and 0. To remove only NULL’s use:
$af = [1, 0, 2, null, 3, 6, 7];
Some of PHP’s array functions play a prominent role in so called functional programming languages, where they show up under a slightly different name:
The array functions mentioned above allow you compose new functions on arrays.
This leads to a style of programming that looks much like algebra, e.g. the Bird/Meertens formalism.
E.g. a mathematician might state
map(f o g) = map(f) o map(g)
the so called «loop fusion» law.
Many functions on arrays can be created by the use of the foldr() function (which works like foldl, but eating up array elements from the right).
I can’t get into detail here, I just wanted to provide a hint about where this stuff also shows up and the theory behind it.
be careful with the above function «array_delete»‘s use of the stristr function, it could be slightly misleading. consider the following:
?>
Which filters all keys with «db» or «smarty» as their name (including objects which have a reference to those variables). The output of the above in a test case I did is the following:
Array
(
[userdata] => Array
(
[sid] => a130e675d380e0e9fe47897922d719ac
[not_in_db] =>
[user_id] => 1
[session_id] => 154
[permissions] => 1
[username] => tester
)
[systemobjects] => Array
(
[db] => **filtered by function**
[smarty] => **filtered by function**
)
)
Hi all,
Here’s a function that will look trough an array, and removes the array member when the search string is found.
if needle is left empty, the function will delete the array members that have no value (this means if it’s empty).
NOTE: It rebuilds the array from scratch, so keys begin with 0, like you would create a new array.
Example:
$array = array(«John», «Doe», «Macy»);
$array = array_clean($array, «doe», false);
print_r($array);
would return:
array
(
[0] => John
[1] => Macy
)
Hopes this helps someone 🙂
The following function modifies the supplied array recursively so that filtering is performed on multidimentional arrays as well, while preserving keys.
array_filter may not be used as it does not modify the array within itself.
Read «callback» parameter note with understanding (as well as «converting to boolean» chapter). Keep in midn, that 0, both:
* integer: 0 and
* float: 0.00
evaluates to boolean FALSE! And therefore all array nodes, that have such value WILL ALSO BE FILTERED by array_filter(), with default call back. Unless you provide your own callback function, that will (for example) filter only empty strings and NULLs, but leave «zeros» untouched.
Some people (including me) might be surprised to find this out.
I was looking for a function to delete values from an array and thought I had found it in array_filter(), however, I *didn’t* want the keys to be preserved *and* I needed blank values cleaned out of the array as well. I came up with the following (with help from many of the above examples):
array_keys
(PHP 4, PHP 5, PHP 7, PHP 8)
array_keys — Возвращает все или некоторое подмножество ключей массива
Описание
Список параметров
Массив, содержащий возвращаемые ключи.
Если указано, будут возвращены только ключи у которых значения элементов массива совпадают с этим параметром.
Определяет использование строгой проверки на равенство (===) при поиске.
Возвращаемые значения
Примеры
Пример #1 Пример использования array_keys()
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 28 notes
It’s worth noting that if you have keys that are long integer, such as ‘329462291595’, they will be considered as such on a 64bits system, but will be of type string on a 32 bits system.
?>
will return on a 64 bits system:
but on a 32 bits system:
I hope it will save someone the huge headache I had 🙂
Here’s how to get the first key, the last key, the first value or the last value of a (hash) array without explicitly copying nor altering the original array:
Since 5.4 STRICT standards dictate that you cannot wrap array_keys in a function like array_shift that attempts to reference the array.
Invalid:
echo array_shift( array_keys( array(‘a’ => ‘apple’) ) );
But Wait! Since PHP (currently) allows you to break a reference by wrapping a variable in parentheses, you can currently use:
echo array_shift( ( array_keys( array(‘a’ => ‘apple’) ) ) );
However I would expect in time the PHP team will modify the rules of parentheses.
There’s a lot of multidimensional array_keys function out there, but each of them only merges all the keys in one flat array.
Here’s a way to find all the keys from a multidimensional array while keeping the array structure. An optional MAXIMUM DEPTH parameter can be set for testing purpose in case of very large arrays.
NOTE: If the sub element isn’t an array, it will be ignore.
output:
array(
‘Player’ => array(),
‘LevelSimulation’ => array(
‘Level’ => array(
‘City’ => array()
)
),
‘User’ => array()
)
array (size=4)
0 => string ‘e’ (length=1)
1 => int 1
2 => int 2
3 => int 0
—-
expected to see:
dude dude dude
Sorry for my english.
I wrote a function to get keys of arrays recursivelly.
Here’s a function I needed to collapse an array, in my case from a database query. It takes an array that contains key-value pairs and returns an array where they are actually the key and value.
?>
Example usage (pseudo-database code):
= db_query ( ‘SELECT name, value FROM properties’ );
/* This will return an array like so:
/* Now this array looks like:
?>
I found this handy for using with json_encode and am using it for my project http://squidby.com
This function will print all the keys of a multidimensional array in html tables.
It will help to debug when you don?t have control of depths.
An alternative to RQuadling at GMail dot com’s array_remove() function:
The position of an element.
One can apply array_keys twice to get the position of an element from its key. (This is the reverse of the function by cristianDOTzuddas.) E.g., the following may output «yes, we have bananas at position 0».
Hope this helps someone.
# array_keys() also return the key if it’s boolean but the boolean will return as 1 or 0. It will return empty if get NULL value as key. Consider the following array:
Array
(
[ 0 ] => first_index
[ 1 ] => 1
[ 2 ] => 0
[ 3 ] => 4
[ 4 ] => 08
[ 5 ] => 8
[ 6 ] =>
)
This function will extract keys from a multidimensional array
Array
(
[color] => Array
(
[1stcolor] => blue
[2ndcolor] => red
[3rdcolor] => green
)
[size] => Array
(
[0] => small
[1] => medium
[2] => large
)
Array
(
[0] => color
[1] => 1stcolor
[2] => 2ndcolor
[3] => 3rdcolor
[4] => size
[5] => 0
[6] => 1
[7] => 2
)
All the cool notes are gone from the site.
Here’s an example of how to get all the variables passed to your program using the method on this page. This prints them out so you can see what you are doing.
Simple ways to prefixing arrays;
[1] => Array
(
[product_id] => 2
[product_name] => Bar
)
I was looking for a function that deletes either integer keys or string keys (needed for my caching).
As I didn’t find a function I came up with my own solution.
I didn’t find the propiest function to post to so I will post it here, hope you find it useful.
?>
You can of course define constants to have a nicer look, I have chosen these: EXTR_INT = 1; EXTR_STRING = 2
EXTR_INT will return an array where keys are only integer while
EXTR_STRING will return an array where keys are only string
A needed a function to find the keys which contain part of a string, not equalling a string.
How to filter an array by a condition
I have an array like this:
Now I want to filter that array by some condition and only keep the elements where the value is equal to 2 and delete all elements where the value is NOT 2.
So my expected result array would be:
Note: I want to keep the keys from the original array.
How can I do that with PHP? Any built-in functions?
9 Answers 9
You somehow have to loop through your array and filter each element by your condition. This can be done with various methods.
Loops while / for / foreach method
Looping
Condition
Just place your condition into the loop where the comment //condition is. The condition can just check for whatever you want and then you can either unset() the elements which don’t meet your condition, and reindex the array with array_values() if you want, or write the elements in a new array which meet the condition.
array_filter() method
Another method is to use the array_filter() built-in function. It generally works pretty much the same as the method with a simple loop.
You just need to return TRUE if you want to keep the element in the array and FALSE if you want to drop the element out of the result array.
preg_grep() method
preg_grep() is similar to array_filter() just that it only uses regular expression to filter the array. So you might not be able to do everything with it, since you can only use a regular expression as filter and you can only filter by values or with some more code by keys.
Also note that you can pass the flag PREG_GREP_INVERT as third parameter to invert the results.
Common conditions
There are many common conditions used to filter an array of which all can be applied to the value and or key of the array. I will just list a few of them here:
array_fill_keys
(PHP 5 >= 5.2.0, PHP 7, PHP 8)
array_fill_keys — Создаёт массив и заполняет его значениями с определёнными ключами
Описание
Список параметров
Массив значений, которые будут использованы в качестве ключей. Некорректные ключи массива будут преобразованы в строку ( string ).
Возвращаемые значения
Возвращает заполненный массив
Примеры
Пример #1 Пример использования array_fill_keys()
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 8 notes
now string key «1» become an integer value 1, be careful.
Some of the versions do not have this function.
I try to write it myself.
You may refer to my script below
RE: bananasims at hotmail dot com
I also needed a work around to not having a new version of PHP and wanting my own keys. bananasims code doesn’t like having an array as the second parameter.
Here’s a slightly modified version than can handle 2 arrays as inputs:
//we want these values to be keys
$arr1 = (0 => «abc», 1 => «def»);
/we want these values to be values
$arr2 = (0 => 452, 1 => 128);
returns:
abc => 452, def =>128
Scratchy’s version still doesn’t work like the definition describes. Here’s one that can take a mixed variable as the second parameter, defaulting to an empty string if it’s not specified. Don’t know if this is exactly how the function works in later versions but it’s at least a lot closer.
This works for either strings or numerics, so if we have
$arr1 = array(0 => ‘abc’, 1 => ‘def’);
$arr2 = array(0 => 452, 1 => 128);
$arr3 = array(0 => ‘foo’, 1 => ‘bar’);
array_fill_keys($arr1,$arr2)
returns: [abc] => 452, [def] => 128
array_fill_keys($arr1,0)
returns: [abc] => 0, [def] => 0
array_fill_keys($arr2,$arr3)
returns: [452] => foo, [128] => bar
array_fill_keys($arr3,’BLAH’)
returns: [foo] => BLAH, [bar] => BLAH
and array_fill_keys($arr1)
returns: [abc] =>, [def] =>