开发者

How can I create a subsection of an existing array using PHP?

I know this is probably a very simple question but I have looked around and most answers relate to array intersections which is not what I am looking for.

Example:

I have an array ($rows). When running print_r($rows) I get:

Array (
  [0] => Array (
    [id] => 184
    [0] => 184
    [name] => Advantage Membership
    [1] => Advantage Membership
    [flag] => 4
    [2] => 4
  )
  [1] => Array (
    [id] =>开发者_如何转开发; 238
    [0] => 238
    [programname] => Package 2
    [1] => Package 2
    [flag] => 5
    [2] => 5
  )
) 

I want to essentially create a 'sub' array which contains all of the 'flag' fields in my $rows array so that I can THEN do a if(in_array()) statement with another value.

ideal result array would look like:

$array2 = array( '4', '5' )

Then I could run the following and be happy:

if (in_array(4, $array2)) ...

Any suggestions?


What's wrong with a custom function?

function in_sub_array($needle, $ary){
  foreach ($ary as $a){
    if (isset($a['flag']) && $a['flag'] == $needle) // could use ===, too.
      return true;
  }
  return false;
}

if (in_sub_arry(4,$array2)) ...

Or, as others have suggested, array_map is a good alternative.

function get_flags($ary){
  return (isset($ary['flag']) ? $ary['flag'] : null);
}

if (in_array(4,array_map('get_flags',$array2))) ...

demos of both methods


function flagit($n)
{
    return $n['flag'];
}

$flags = array_map("flagit", $array);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜