首页 > 解决方案 > 数组数组中的数组

问题描述

我需要帮助,我无法将数组数组中的单个值分配给变量。

$arr_categories = array(
    array(1,"category_1",

            01=>"product name 1", 20 . "€"=> "description 1.",
            02=>"product name 2", 25 . "€"=> "description 2.",
            03=>"product name 3", 12 . "€"=> "description 3.",
            04=>"product name 4", 33 . "€"=> "description 4.",
            05=>"product name 5", 36 . "€"=> "description 5.",
        
    ),
    array(2,"category_2",

            01=>"product name 1", 20 . "€"=> "description 1.",
            02=>"product name 2", 25 . "€"=> "description 2.",
            03=>"product name 3", 12 . "€"=> "description 3.",
            04=>"product name 4", 33 . "€"=> "description 4.",
            05=>"product name 5", 36 . "€"=> "description 5.",
    
    ), 
    array(3,"category_3",

            01=>"product name 1", 20 . "€"=> "description 1.",
            02=>"product name 2", 25 . "€"=> "description 2.",
            03=>"product name 3", 12 . "€"=> "description 3.",
            04=>"product name 4", 33 . "€"=> "description 4.",
            05=>"product name 5", 36 . "€"=> "description 5.",
      
    )
);

我可以将第二维数组的值分配给单个变量,如下所示:

for ($i=0;$i<count($arr_categories);$i++){
    $category = $arr_categorie[$i];
    $category_id = $category[0];
    $category_name = $category[1];

但是如何使用第二个循环来计算和提取产品的单个值?我尝试了第二个“for”循环,“foreach”,但没有任何效果。有人有建议吗?是否有可能我必须修改我的多维数组的 sintax?

希望能帮到你,谢谢!:-)

标签: phparraysmultidimensional-array

解决方案


我建议您添加另一层嵌套,将所有产品放在它们自己的数组中,而不是放在类别数组本身中。此外,您可以使内部数组关联而不是硬编码特定位置。

你最里面的数组也需要更好的结构。我不明白为什么您会使用价格作为返回描述的键。您应该有单独的价格和描述键。

$arr_categories = array(
    array('id' => 1,
          'name' => "category_1",
          'products' => array(
            array('name' => "product name 1", 'price' => "20€&quot;, 'description' => "description 1."),
            array('name' => "product name 2", 'price' => "25€&quot;, 'description' => "description 2."),
            ...
          )
    ),
    ...
);

那么你的循环可以是:

foreach ($arr_categories as $category) {
    $category_id = $category['id'];
    $category_name = $category['name'];
    $category_products = $category['products'];
    ...
}

推荐阅读