I
I
IceJOKER2015-09-28 12:18:27
PHP
IceJOKER, 2015-09-28 12:18:27

How to group similar array elements?

Hello, there is an array of values ​​that are sorted by the key order , you need to go through the array and display the values ​​in a div . ( data is taken from the database and already sorted! )

$items= array(
    array("order" => 1), 
    array("order" => 2), 
    array("order" => 2), 
    array("order" => 3), 
    array("order" => 4)
);
--- multidimensional array, typo, thanks 27cm
need to get the following
<div>1</div>
<div>22</div>
<div>3</div>
<div>4</div>

ps values ​​are not always sequential, i.e. for example after 4 can be 10 or 100

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
IceJOKER, 2015-09-28
@IceJOKER

Somehow I did it myself:

$last_order = -1;
foreach($items as $item){
  if($last_order != -1 && $item['order'] != $last_order)
  {
    echo '</div>';
  }
  if($item['order'] != $last_order)
  {
    echo '<div>';
    $last_order = $item['order'];
  }
  echo $item['order'];
  
}

phpfiddle.org/lite/code/rf61-69wv

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question