Php array filtering hypothesis array (0 & nbsp ;=& gt; & nbsp; array ('catid' & nbsp ;=& gt; & nbsp; 10 & nbsp ;, & nbsp; 'parent' & nbsp ;=& gt; & nbsp; '1') & nbsp;, & nbsp; 1 & nbsp ;=& gt; & nbsp; array ('catid' & php array filtering
Suppose the array
Array (0 => array ('catid' => 10, 'parent' => '1'), 1 => array ('catid' => 11, 'parent' => 1), array ('catid' => 21, 'parent' => 2 ));
What should I do if I want to keep only the value of parent 2?
Thank you!
Php
------ Solution --------------------
$ A = array (0 => array ('catid' => 10, 'parent' => '1'), 1 => array ('catid' => 11, 'parent' => 1), array ('catid' => 21, 'parent' => 2 ));
$ T = array_map (function ($ v) {return array ('parent' => $ v ['parent']) ;}, $ );
/*
Php 5.2.x writing
$ T = array_map (create_function ('$ V', 'Return array ("parent" => $ v ["parent"]);'), $ );
*/
Print_r ($ t );Array
(
[0] => Array
(
[Parent] => 1
)
[1] => Array
(
[Parent] => 1
)
[2] => Array
(
[Parent] => 2
)
)
------ Solution --------------------
Function intersect2nd ($ arr1, $ arr2, $ key)
{
Foreach ($ arr2 as $ v) $ tmpArr [] = $ v [$ key];
Foreach ($ arr1 as $ k => $ v) if (in_array ($ v [$ key], $ tmpArr) $ arr [$ k] = $ v;
Return $ arr;
}
$ A = array (0 => array ('catid' => 10, 'parent' => '1'), 1 => array ('catid' => 11, 'parent' => 1), array ('catid' => 21, 'parent' => 2 ));
$ B = array ('parent' => 2); // you can compile a similar array containing the required key and value.
$ C = intersect2nd ($ a, $ B, 'parent ');
Var_export ($ c );
In my memory, this is the moderator's nagging code.