数组数据在PHP中过滤

时间:2013-06-10 09:14:24

标签: php arrays filter

我有一个如下所示的数组 -

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
    )
)

我只想获取包含我指定的特定值的数组,例如,我想获取包含键'name'='3Dmodel'的值的数组。对于上面的例子,我想只得到数组 -

[0] => Array (
   [name] => 3DModel
   [url] => /psde/img/lanai-1024x480.jpg
   )
[2] => Array (
   [name] => 3DModel
   [url] => psde/img/home-1024x480.jpg
   )

有没有办法做到这一点?......像这样的事情

$arr = array( 'element1' => 1, 'element2' => 2, 'element3' => 3, 'element4' => 4 );
$filterOutValue = array( 2, 4 );

3 个答案:

答案 0 :(得分:3)

试试这个。

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;
}

通过

打电话
$new_arr = filter_array($arr,'3DModel','name');

答案 1 :(得分:0)

试试这个:

$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);

答案 2 :(得分:0)

试试这个。

$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>";