Как я могу установить многомерный цикл foreach в php?

1

У меня две циклы foreach и ее работа отлично. Но мне нужны данные в другом формате. Пожалуйста, просмотрите код ниже.

Код

$data['categories'] = array();
foreach ($allCategories as $result) {
        $data['categories'][] = array(
                'name' => $result['name'],
                'Cat_id' => $result['category_id']
        );
        $productData= $this->model_catalog_product->getProducts($productID);
        foreach ($productData as $singleProduct) {


            $data['categories'][] = array(
                'product_id'  => $singleProduct['product_id'],
                'thumb'       => $image,
                'name'        => $singleProduct['name'],
                'description' => utf8_substr(strip_tags(html_entity_decode($singleProduct['description'], ENT_QUOTES, 'UTF-8')), 0, $this->config->get('config_product_description_length')) . '..',
                'price'       => $price,
                'special'     => $special,
                'tax'         => $tax,
                'minimum'     => $singleProduct['minimum'] > 0 ? $singleProduct['minimum'] : 1,
                'rating'      => $rating,
                'href'        => $this->url->link('product/product', 'product_id=' . $singleProduct['product_id'])
            );

         }

    }

результат

Array
(
    [0] => Array
        (
            [name] => sweflora special
            [Cat_id] => 59
        )

    [1] => Array
        (
            [product_id] => 52
            [thumb] => http://localhost/swefloraProject/upload/image/cache/catalog/birthday/home-product-01-80x80.png
            [name] => gift flowers
            [description] => when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has ..
            [price] => $0.00
            [special] => 
            [tax] => $0.00
            [minimum] => 1
            [rating] => 0
            [href] => http://localhost/swefloraProject/upload/index.php?route=product/product&product_id=52
        )

    [2] => Array
        (
            [name] => birthday
            [Cat_id] => 61
        )

    [3] => Array
        (
            [product_id] => 53
            [thumb] => http://localhost/swefloraProject/upload/image/cache/catalog/birthday/flower2-80x80.jpg
            [name] => test flower
            [description] => ..
            [price] => $86.00
            [special] => 
            [tax] => $86.00
            [minimum] => 1
            [rating] => 0
            [href] => http://localhost/swefloraProject/upload/index.php?route=product/product&product_id=53
        )
  )

Я хочу изменить формат массива. В настоящее время он напрямую показывает категории и продукты. Но мне нужен такой массив, как этот формат.

Array
(
    [0] => Array
        (
            [name] => sweflora special
            [Cat_id] => 59

           [Products] =>  Array
            (
                [product_id] => 52
                [thumb] => http://localhost/Project/upload/image/cache/catalog/birthday/home-product-01-80x80.png
                [name] => gift flowers
                [description] => when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has ..
                [price] => $0.00
                [special] => 
                [tax] => $0.00
                [minimum] => 1
                [rating] => 0
                [href] => http://localhost/Project/upload/index.php?route=product/product&product_id=52
            )
            [Products] =>  Array
            (
                [product_id] => 52
                [thumb] => http://localhost/swefloraProject/upload/image/cache/catalog/birthday/home-product-01-80x80.png
                [name] => gift flowers
                [description] => when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has ..
                [price] => $0.00
                [special] => 
                [tax] => $0.00
                [minimum] => 1
                [rating] => 0
                [href] => http://localhost/Project/upload/index.php?route=product/product&product_id=52
            )
        )

      [1] => Array
        (
            [name] => sweflora special
            [Cat_id] => 60

           [Products] =>  Array
            (
                [product_id] => 52
                [thumb] => http://localhost/Project/upload/image/cache/catalog/birthday/home-product-01-80x80.png
                [name] => gift flowers
                [description] => when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has ..
                [price] => $0.00
                [special] => 
                [tax] => $0.00
                [minimum] => 1
                [rating] => 0
                [href] => http://localhost/Project/upload/index.php?route=product/product&product_id=52
            )
            [Products] =>  Array
            (
                [product_id] => 52
                [thumb] => http://localhost/Project/upload/image/cache/catalog/birthday/home-product-01-80x80.png
                [name] => gift flowers
                [description] => when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has ..
                [price] => $0.00
                [special] => 
                [tax] => $0.00
                [minimum] => 1
                [rating] => 0
                [href] => http://localhost/Project/upload/index.php?route=product/product&product_id=52
            )
        )


  )

Я использовал array_push и array_combine но решил эту проблему. Может ли кто-нибудь мне посоветовать, как я могу конвертировать в этот формат. благодаря

Теги:
arrays
multidimensional-array
foreach

1 ответ

1
Лучший ответ

По-моему, вложенные foreach должны добавлять элементы к новому внутреннему массиву для каждой категории. Вы не можете получить точно такую структуру, которую вы разместили, в которой вы связываете ключ "Продукты" с несколькими объектами, но вместо этого вы можете построить вложенный массив продуктов. Поэтому я бы постарался:


    foreach ($productData as $singleProduct) {
        $data['categories']['Products'][] = array(/* Your element */);

Изменение: нам нужно сохранить привязку к категории, поэтому я бы сделал:

$i=0;
foreach ($allCategories as $result) {
    $data['categories'][$i] = array(
            'name' => "N",
            'Cat_id' => "C",
            'Products' => array()
    );
    $productData= $this->model_catalog_product->getProducts($productID);
    foreach ($productData as $singleProduct){
        $data['categories'][$i]['Products'][] = array(
            /* Your product */);

     }
$i++;
}
  • 0
    спасибо, но формат массива все еще не правильный. Потому что все продукты показаны в первой категории.
  • 0
    Я редактирую ответ: в основном в моем предыдущем решении не было никакой границы между категорией и продуктами ... с помощью индекса мы добавляем продукт в соответствующую категорию (без слишком большого изменения вашего кода). Он должен работать даже без предварительного объявления поля «Продукты» в качестве массива
Показать ещё 1 комментарий

Ещё вопросы

Сообщество Overcoder
Наверх
Меню