three objects that are stored in the variable image

 object(ImageClass)#1 (1){ ["name"]=>"one"; ["forHome"]=>0; } object(ImageClass)#1 (2){ ["name"]=>"two"; ["forHome"]=>1; } object(ImageClass)#1 (3){ ["name"]=>"three"; ["forHome"]=>0; } 

I need to withdraw foreach tic so? that the object with the forHome value is 0 first is displayed relatively speaking of such code

 foreach($image as $img){ 'Name :". $img->name ." for home :".$img->forHome } 
  • What is the catch then? - teran
  • @teran corrected - Sergalas
  • duck, add objects into an array, if they are not already in an array, sort using usort and output. - teran

2 answers 2

If you take your original class of the following form:

 class Image { public $name; public $forHome; } 

Generate a test array:

 $data = []; $n = rand(3,10); while($n--){ $img = new Image(); $img->name = "image-$n"; $img->forHome = rand(0,1); $data[] = $img; } 

then further it is necessary to sort the array by the value of your object field. For these purposes, the usort() function is used, the first argument of which is a sortable array passed by reference, the second is the callback function, which takes as argument 2 values ​​from the array (object) and compares them. It is necessary to compare the values. In such a function, it is customary to return the value 0 if the elements are equal, or the values 1 or -1 , in the case of more / less. More often just return the difference between them. In PHP7, a special operator <=> introduced for this purpose:

 usort($data, function($a, $b){ return $a->forHome - $b->forHome; }); 

Obviously, if the order of the elements needs to be preserved, and only output the "zero" elements at the beginning, then sorting will not be the right solution for the problem. Although if the numbering of objects is stored, then this is enough. Otherwise, you can move the elements with a zero value forward of the array, for example, as follows:

 $result = ['zero' => null, 'nonzero' => null]; foreach($data as $img){ $key = $img->forHome ? 'nonzero' : 'zero'; $result[$key][] = $img; } $data = array_merge($result['zero'], $result['nonzero']); 

In this case, the original order of the elements will be preserved.

Of course, a trite problem can be solved with two output cycles. In the first output only zero, and in the second in reverse.

     $images = array(/* ваши объекты */); usort($images, function($a, $b) { if ($a->forHome == $b->forHome) return 0; else (return $a->forHome > $b->forHome) ? 1 : -1; });