O
O
Optimus2018-02-14 16:21:57
PHP
Optimus, 2018-02-14 16:21:57

How to output/convert an array?

There is an array:

array(6) {
  [0]=>
  array(2) {
    ["title"]=>
    string(23) "Товар 1"
    ["theme"]=>
    string(5) "Кастрюли"
  }
  [1]=>
  array(2) {
    ["title"]=>
    string(23) "Товар 2"
    ["theme"]=>
    string(5) "Кастрюли"
  }
  [2]=>
  array(2) {
    ["title"]=>
    string(20) "Товар 3"
    ["theme"]=>
    string(14) "Сковородки"
  }
  [3]=>
  array(2) {
    ["title"]=>
    string(20) "Товар 4"
    ["theme"]=>
    string(14) "Сковородки"
  }
  [4]=>
  array(2) {
    ["title"]=>
    string(31) "Товар 5"
    ["theme"]=>
    string(6) "Кружки"
  }
  [5]=>
  array(2) {
    ["title"]=>
    string(31) "Товар 6"
    ["theme"]=>
    string(6) "Кружки"
  }
}

What's the best way to display it like this:
<b>Кастрюли</b>
<ul>
  <li>Товар 1
  <li>Товар 2
</ul>

<b>Сковородки</b>
<ul>
  <li>Товар 3
  <li>Товар 4
</ul>

<b>Кружки</b>
<ul>
  <li>Товар 5
  <li>Товар 6
</ul>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Mashletov, 2018-02-14
Pyan @marrk2

<?php

$list = []; // ваш массив
$p = [];

foreach ($list as $item) {
    if (!isset($p[$item['theme']])) {
        $p[$item['theme']] = [];
    }
    
    $p[$item['theme']][] = $item['title'];
}

/*
 * теперь $p будет иметь вид:
 * 
 * [
 *      'Кастрюли' => ['Товар1', 'Товар3', 'Товар2', ]
 *      'Чашки' => ['Чашка 1', 'Чашка 2']
 * ]
 * 
 * дальше сами
 * foreach ($p as $title => $items) {
 *      foreach ($items as $item) {
 *        // и т д
 *      }
 * }  
 */

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question