Good day. There is an array:
array
(
[34612] = & gt; Array.
(
[ID] = & gt; 34612.
[Name] = & gt; White-green
[SORT] = & GT; 500.
)
[34615] = & gt; Array.
(
[ID] = & gt; 34615.
[Name] = & gt; White-red-gray
[SORT] = & GT; 500.
)
[155] = & gt; Array.
(
[ID] = & gt; 155.
[Name] = & gt; White-red-blue
[SORT] = & GT; 500.
)
[161] = & gt; Array.
(
[ID] = & gt; 161.
[Name] = & gt; White-red-black
[SORT] = & GT; 500.
)
)
and there are keys 155 161 they mean that these elements of the array must remain, all other are needed.
How to organize it right?
Answer 1, Authority 100%
Let $ Array
– your array.
For this case, the simplest thing:
unset ($ array [34612]);
Unset ($ array [34615]);
But it’s better a universal option when you can easily change the allowed keys, and unresolved keys are not known in advance (for example, too much):
$ allowed = [155, 161]; // Allowed keys
$ Filtered = Array_Filter (
$ array,
Function ($ Key) Use ($ Allowed) {
Return in_array ($ Key, $ Allowed);
},
Array_Filter_use_Key.
); // Now in an array $ Filtered only elements with authorized keys
but Flag Array_Filter_use_Key
Added to PHP version 5.6. If you apply an earlier version, you can use less flexible, but even more convenient option:
$ filtered = array_intersect_key ($ array, array_flip ($ allowed));
Answer 2, Authority 12%
// $ array - your array
$ result = array (); // New Filtered Array
Foreach ($ Array As $ Key = & GT; $ value) {
if ($ Key! == 161 & amp; & amp; $ key! == 155)
$ result [] = $ value;
}
Answer 3, Authority 12%
In the loop we pass all the elements of the array, if the key of these elements is not 155 and not 161 – delete
foreach ($ arr as $ key = & gt; $ value) {
If ($ Key! = '155' and $ Key! = '161') {
Unset ($ Arr [$ Key]);
}
}