Reputation: 711
I have an array like below -
Array (
[0] => Array (
[name] => 3DModel
[url] =>psde/img/lanai-1024x480.jpg
)
[1] => Array (
[name] => BuilndingModel
[url] => psde/img/lot34-front.jpg
)
[2] => Array (
[name] => 3DModel
[url] => psde/img/home-1024x480.jpg
)
)
I just want to fetch out arrays that containing a particular value I specify, for example, I want to fetch out array that contains the value for key 'name' = '3Dmodel'. For above example I want to get only arrays -
[0] => Array (
[name] => 3DModel
[url] => /psde/img/lanai-1024x480.jpg
)
[2] => Array (
[name] => 3DModel
[url] => psde/img/home-1024x480.jpg
)
Is there any way to do this?
Upvotes: 1
Views: 285
Reputation: 32721
Try this one.
$myarray = array (
0 => array (
'name' => '3DModel',
'url' =>'psde/img/lanai-1024x480.jpg'
),
1 => array (
'name' => 'something',
'url' => 'psde/img/lot34-front.jpg'
),
2 => array (
'name' => '3DModel',
'url' => 'psde/img/home-1024x480.jpg'
),
);
$newarray=array();
foreach($myarray as $key=>$item)
{
if($item['name']==='3DModel'){
$newarray[$key]=$item;
}
}
echo "<pre>";
print_r ($newarray);
echo "</pre>";
Upvotes: 0
Reputation: 5012
Try this.
function filter_array($arr,$value,$key)
{
$new_arr = array();
foreach($arr as $arr_res)
{
if($arr_res[$key]==$value)
{
$new_arr[] = $arr_res;
}
}
return $new_arr;
}
And call by
$new_arr = filter_array($arr,'3DModel','name');
Upvotes: 3
Reputation: 46
Try this :
$arr = array( 'element1' => 1, 'element2' => 2, 'element3' => 3, 'element4' => 4 );
$filterOutValue = array( 2, 4 );
$arrResult = array();
foreach($filterOutValue AS $value) {
foreach($arr AS $kArr => $vArr) {
if($value == $vArr) {
$arrResult[$kArr] = $vArr;
break;
}
}
}
print_r($arrResult);
Upvotes: 0