在for循环中执行一次值

时间:2019-05-03 10:49:41

标签: php

在具有2次的数组列表[hide] => 1中,如何仅在for循环中执行一次[hide] => 1。如何检查所有先前值和[hide] => 1的当前数组在for循环中执行一次

需要执行[id] => 4,无需在for循环中执行[id] => 2

数组

Array ( 
    [0] => Array ( [id] => 6 [hide] => 0  ) 
    [1] => Array ( [id] => 5  [hide] => 0 )
    [2] => Array ( [id] => 4  [hide] => 1 )
    [3] => Array ( [id] => 3  [hide] => 0  )
    [4] => Array ( [id] => 2 [hide] => 1  )
)

3 个答案:

答案 0 :(得分:0)

for($i = 0; $i<count($array); $i++){

  if($array[$i] == 4){
       print_r($array[4]);
   }
}

答案 1 :(得分:0)

尝试一下.....您可以在关联数组的任何深度使用此功能。

 function is_in_array($array, $key, $key_value){
    $within_array = 'no';
    foreach( $array as $k=>$v ){
      if( is_array($v) ){
          $within_array = is_in_array($v, $key, $key_value);
          if( $within_array == 'yes' ){
              break;
         }
      } else {
             if( $v == $key_value && $k == $key ){
                     $within_array = 'yes';
                     break;
             }
        }
     }
      return $within_array;
   }
   print_r(is_in_array($yourarray, 'hide', '1'));

答案 2 :(得分:0)

我想您想要ID最大的商品:

// get only the items with 'hide' = 1
$hidden = array_filter($array, function($item){return $item['hide'] == 1;});

// order the array to have the items with the greatest ID first
usort($hidden, function($a, $b){
    return $b['id'] - $a['id'] ;
});

// print the item with the max id 
print_r($hidden[0]);