解析PHP中的多维数组项

3
我正在创建一家电子商务网站,需要在特定数组中提供商店所拥有的类别。目前从mysql表中检索到的数据如果数组具有不同的子类,则包含相同类别ID的不同数组项。我必须将相同类别ID收集在同一个数组中,并为子类创建嵌套数组。此代码位于laravel 4.2上。以下是当前数据格式:
"data": [
    {
      "id": 1,
      "name": "Fruits",
      "sub_category_names": [
        "Dairy Whiteners"
      ],
      "total_items": 69
    },
    {
      "id": 1,
      "name": "Fruits",
      "sub_category_names": [
        "Tea & Coffee"
      ],
      "total_items": 69
    },
    {
      "id": 1,
      "name": "Fruits",
      "sub_category_names": [
        "Concentrates - Tang etc"
      ],
      "total_items": 69
    },
    {
      "id": 2,
      "name": "Beverages",
      "sub_category_names": [
        "Tea & Coffee"
      ],
      "total_items": 28
    },
    {
      "id": 2,
      "name": "Beverages",
      "sub_category_names": [
        "Concentrates - Tang etc"
      ],
      "total_items": 28
    }
  ]

Here is what I need ,

"data": [
    {
      "id": 1,
      "name": "Fruits",
      "sub_category_names": [
        "Dairy Whiteners" , "Concentrates - Tang etc" , "Tea & Coffee"
      ],
      "total_items": 69
    } ,

    {
      "id": 2,
      "name": "Beverages",
      "sub_category_names": [
        "Tea & Coffee" , "Concentrates - Tang etc"
      ],
      "total_items": 28
    }
  ]

The code I wrote for the above ,

// For the current categories create a common array for subcategories for same categories
        $filteringSelectedCategories = [];
        $subCategoriesNamesLocal = [];
        $innerIndex = 0;
        for ($i = 0; $i < count($selectedCategories); $i++) {

            // to prevent undefined offset error
            if (!isset($selectedCategories[$i + 1])) {
                continue ;
                // if 6 don't exist then deal with 5
            }
            // if the id of two items is same then push that sub category name in the same array
            if ($selectedCategories[$i]['id'] === $selectedCategories[$i + 1]['id']) {
                array_push($subCategoriesNamesLocal, $selectedCategories[$i]['sub_category_names']);
            } 
            // if the id is different then push the array values with the sub category name in an array 
            else {

                $filteringSelectedCategories[$innerIndex]['id'] = $selectedCategories[$i]['id'];
                $filteringSelectedCategories[$innerIndex]['name'] = $selectedCategories[$i]['name'];
                $filteringSelectedCategories[$innerIndex]['sub_category_names'] = $subCategoriesNamesLocal;
                $filteringSelectedCategories[$innerIndex]['total_items'] = $selectedCategories[$i]['total_items'];

                // nullify the array after assigning the value
                $subCategoriesNamesLocal = [];
                // increment the new array index
                $innerIndex = $innerIndex + 1;

            }
        }

以下是我从上述代码中获得的输出结果:
"data": [
    {
      "id": 1,
      "name": "Fruits",
      "sub_category_names": [
        [
          "Dairy Whiteners"
        ],
        [
          "Tea & Coffee"
        ]
      ],
      "total_items": 69
    }
  ]

1
如果你正在使用MySQL,我认为GROUP_CONCAT可以解决这个问题。请展示一下你如何获取数据。 - Mihai
3个回答

2

我不完全确定偏移错误可能会出现什么情况,但我相信你可以轻松解决;

foreach ($selectedCategories as $key => $data) {
    $newKey = $data['id'];
    $filteringSelectedCategories[$newKey]['id'] = $data['id'];
    $filteringSelectedCategories[$newKey]['name'] = $data['name'];
    $filteringSelectedCategories[$newKey]['sub_category_names'][] = $data['sub_category_names'];
    $filteringSelectedCategories[$newKey]['total_items'] = $data['total_items'];
}

PHP有foreach来迭代数组中的元素,而不是使用for。 - Siddharth Sharma
以下是我在应用上述解决方案后得到的工作结果:"data":[ { "id":1, "name":"水果", "sub_category_names":[ "奶精", "茶和咖啡", "浓缩饮料-Tang等" ], "total_items":69 }, { "id":2, "name":"饮料", "sub_category_names":[ "茶和咖啡", "浓缩饮料-Tang等" ], "total_items":28 } ] - Siddharth Sharma
抱歉,我的错。已经更新帖子为foreach。感谢你的指出。 - glend

0

你不能直接在 $subCategoriesNamesLocal 中进行数组推送,因为你正在嵌套数组。请先创建一个数组,然后将其连接到该字段。


0

试试这个:

// For the current categories create a common array for subcategories for same categories
        $filteringSelectedCategories = [];
        $subCategoriesNamesLocal = [];
        $innerIndex = 0;
        for ($i = 0; $i < count($selectedCategories); $i++) {

            // to prevent undefined offset error
            if (!isset($selectedCategories[$i + 1])) {
                continue ;
                // if 6 don't exist then deal with 5
            }
            // if the id of two items is same then push that sub category name in the same array
            if ($selectedCategories[$i]['id'] === $selectedCategories[$i + 1]['id']) {
                array_push($subCategoriesNamesLocal, $selectedCategories[$i]['sub_category_names']);
            } 
            // if the id is different then push the array values with the sub category name in an array 
            else {

                $filteringSelectedCategories[$innerIndex]['id'] = $selectedCategories[$i]['id'];
                $filteringSelectedCategories[$innerIndex]['name'] = $selectedCategories[$i]['name'];
                $filteringSelectedCategories[$innerIndex]['sub_category_names'] = '"' . implode('","', $subCategoriesNamesLocal) . '"';

}
                $filteringSelectedCategories[$innerIndex]['total_items'] = $selectedCategories[$i]['total_items'];

                // nullify the array after assigning the value
                $subCategoriesNamesLocal = [];
                // increment the new array index
                $innerIndex = $innerIndex + 1;

            }
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接