首页 > 解决方案 > 在 for 循环中执行一次值

问题描述

在数组列表 [hide] =>1 中有 2 次,如何在 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  )
)

标签: php

解决方案


我想您想要具有最大 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]);

推荐阅读