php - 数组数组中的数组
问题描述
我需要帮助,我无法将数组数组中的单个值分配给变量。
$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?
希望能帮到你,谢谢!:-)
解决方案
我建议您添加另一层嵌套,将所有产品放在它们自己的数组中,而不是放在类别数组本身中。此外,您可以使内部数组关联而不是硬编码特定位置。
你最里面的数组也需要更好的结构。我不明白为什么您会使用价格作为返回描述的键。您应该有单独的价格和描述键。
$arr_categories = array(
array('id' => 1,
'name' => "category_1",
'products' => array(
array('name' => "product name 1", 'price' => "20€", 'description' => "description 1."),
array('name' => "product name 2", 'price' => "25€", 'description' => "description 2."),
...
)
),
...
);
那么你的循环可以是:
foreach ($arr_categories as $category) {
$category_id = $category['id'];
$category_name = $category['name'];
$category_products = $category['products'];
...
}
推荐阅读
- python - 将python日历插入tkinter标签
- r - R Shiny - 获取单选按钮的标签
- ios - UILabel 子类的 TextColor
- html - on hover mega menu not displaying
- python - Installing pyfluidsynth on windows
- java - org.hibernate.exception.GenericJDBCException: could not extract ResultSet
- python - pytorch autoencoder model evaluation fail
- javascript - 为什么对 string.charCodeAt() 的两次调用比在从未达到的情况下一次调用一次更快?
- javascript - How to post select box and not the value of select box
- python - 无法在 Django Rest Framework 中查找具有外键子字段的字段