2

是否有某种类型的选择功能来创建一个新数组,只选择具有匹配情况的子元素的某些元素?例如,我只想有一个包含 [type] 为“A”的数组,所以最终的数组只包含 [1] 和 [2]。

[1]  
    [type] => A
    [month] => January

[2]
    [type] => A
    [month] => February

[3]
    [type] => B
    [month] => March

谢谢!

4

4 回答 4

2
function is_type_a($element) { return $element['type'] === 'A'; }
$fiteredArray = array_filter($inputArray, 'is_type_a');

如果你有 PHP 5.4,你可以用匿名函数更简洁地做到这一点。

于 2012-05-04T01:20:28.870 回答
1

您可以将该数组简化为您想要的条目。请记住,这将保留原始键,因此如果在此过程中未设置 2,您最终可能会得到一个包含 0、1 和 3 作为键的数组。

foreach( $array as $key => &$value ){
  if ( $value['type'] != 'A' )
    unset( $array[ $key ] );
}

演示:http ://codepad.org/OG5rguJ8

另一种方法是使用array_filter迭代地减少数组一次一个条目:

function callbackFunc( $val ) {
    return $val['type'] == 'A';
}

$result = array_filter( $array, callbackFunc );

We call the array_filter method passing in the array we'd like to filter, as well as the filtering function we've created. Our function will be ran against each element within the array, treating the current element as a $val variable.

If that variable's type key maps to a value that is == to "A", TRUE is returned. Otherwise, FALSE is returned. When the function returns TRUE, the evaluated value is sent to the $result array. If FALSE was returned, the value is not pushed onto the $result array.

Like the previous option, this method will also preserve the key values.

Demo: http://codepad.org/todHBZo7

于 2012-05-04T01:46:29.527 回答
0
function select_custom($array,$param)
{
    foreach($array as $k=>$v)
    {
       if($v['type']==$param)
       {
          $returnArray[] = $v; 
       }
    }
    return $returnArray;
}
于 2012-05-03T23:50:32.847 回答
0

You can use array_splice() if you know the indexes of the elements you want to pick, if not as suggested by previous answers, you have to loop

于 2012-05-04T01:48:46.843 回答