如何存储id和放在foreach循环php的末尾


How to store id and put to the end of foreach loop php

我正在寻找一个解决方案,把一个指定的id循环结束。

主要问题,id并不总是在DESC顺序或ASC,所以我不能使用这个条件。

$array = array(
  'id' => 3,
  'id' => 4,
  'id' => 2,
  'id' => 8
);
$specifiedId = 2; //can be 3, 4 or 8, it depends on what user define
foreach($array as $data){
 if($data->id == $specifiedId){
   //store this id and move to the end of loop, do nothing yet
 }
 //do the job for id 3 4 and 8, update some data let say...
 ...
 //Ok, i have updated the data on id 3 4 and 8, now lets update the data for the $specifiedId
}

是否有办法把指定的id到循环结束?

是。试试这个

<?php
$array = array(3,4,2,8);
$specifiedId = 2;
$t = count($array);
foreach($array as $key => $data){
 if($data == $specifiedId){
   $desired_id = $key;
 }
 if($key == $t - 1){//last iteration of the loop
 //now use your $desired_id here as reuired
  $desired_id;
 }
}
?>

如果在循环过程中找到数组中的项,则可以将其保存在变量中,然后在循环结束后对该变量进行操作。

$specifiedId = 2; //can be 3, 4 or 8, it depends on what user define
$specific_object = null;
foreach ($array as $data) {
    if ($data->id == $speficiedId) {
        //store this id and move to the end of loop, do nothing yet
        $specific_object = $data;
    } else {
        //do the job for id 3 4 and 8, update some data let say...        
        do_something_with($data);
    }
}
//Ok, i have updated the data on id 3 4 and 8, now lets update the data for the $speficiedId
if ($specific_object) do_something_with($specific_object);