There is an array

array(3) { [0] => array(2) { ["name"] => string(13) "Имя 1" ["group"] => string(22) "Значение 1" } [1] => array(2) { ["name"] => string(13) "Имя 2" ["group"] => string(26) "Значение 2" } [2] => array(2) { ["name"] => string(13) "Имя 3" ["group"] => string(22) "Значение 1" } } 

PHP script:

 <?php foreach ($product_filters as $product_filter) { ?> <div> <?php echo $product_filter['group']; ?> - <?php echo $product_filter['name']; ?> </div> <?php } ?> 

It is necessary to output in one div arrays c "Value 1", and in the other c "Value 2" and so on, what would happen like this

 <div> Имя 1 - Значение 1 Имя 3 - Значение 1 </div> <div> Имя 2 - Значение 2 </div> и т.д... 
  • where does the data come from? - Ipatiev

3 answers 3

You can do the following:

 <?php $product_filters[0]["name"] = "Имя 1"; $product_filters[0]["group"] = "Значение 1"; $product_filters[1]["name"] = "Имя 2"; $product_filters[1]["group"] = "Значение 2"; $product_filters[2]["name"] = "Имя 3"; $product_filters[2]["group"] = "Значение 1"; $items = []; foreach($product_filters as $product_filter) { $items[$product_filter["group"]][] = $product_filter; } ksort($items); foreach($items as $group) { echo "<div>"; foreach($group as $filter) { echo "{$filter['group']} - {$filter['name']}<br />"; } echo "</div>"; } 
     $data = [ [ "name" => "Имя 1", "group" => "Значение 1" ], [ "name" => "Имя 2", "group" => "Значение 2" ], [ "name" => "Имя 3", "group" => "Значение 1" ], ]; $product_filters = []; foreach ($data as $row) { $product_filters[$row['group']][] = $row['name']; } foreach ($product_filters as $group => $names) { echo '<div>'; foreach ($names as $name) { echo $name.' - '.$group.'<br>'; } echo '</div>'; } 

      You can also use array_walk () .

      php> = 5.4

       $inputArray = [ ['name' => 'Имя 1', 'group' => 'Значение 1'], ['name' => 'Имя 2', 'group' => 'Значение 1'], ['name' => 'Имя 3', 'group' => 'Значение 2'], ]; $resultArray = []; array_walk($inputArray, function($item, $key) use (&$resultArray) { $resultArray[$item['group']][] = $item; }); var_dump($resultArray);