【发布时间】:2022-10-08 06:29:14
【问题描述】:
所以我试图拥有一个具有数组值的关联键。并且每当我在 Map 中找到一个不是键的新值时,它应该使用空数组的值初始化键,否则如果键已经存在则添加到该值数组
这是代码,还有 cmets 以便于阅读。
谢谢!
<?php
include_once("./array.php");
?>
<?php
$categories = [];
$categoryMap=array();
#map to find with the category as the key then the item as the value
foreach ($items as $key => $value) {
# code...
$currentCategories = $value['categories'];
for ($i = 0; $i < sizeof($currentCategories); $i++) {
# code...
// if not in keys for the categoryMap then initialize with the key with a value of an empty array
// otherwise just add the the array of values using that keys
// visual of how it should be
// [
// 'buger':['bun','tomato','sauce']
// ]
array_push($categories, $currentCategories[$i]);
}
}
$categories = array_unique($categories);
这是输入数组
<?php
$items = array(
array("itemName" => "Hat", "price" => 10.99, "categories" => ["apparel", "head"]),
array("itemName" => "Scarf", "price" => 7.99, "categories" => ["apparel", "neck"]),
array("itemName" => "Watch", "price" => 19.99, "categories" => ["jewelry", "electronics"]),
array("itemName" => "Necklace", "price" => 99.99, "categories" => ["jewelry", "neck"]),
array("itemName" => "Headphones", "price" => 29.99, "categories" => ["head", "electronics"])
);
【问题讨论】:
-
请写下您的输入和 $items 是什么?
-
@GiacomoM 我刚刚编辑了它。谢谢!!
-
@LawrenceCherone 可以工作,但由于没有初始化的空数组,它不会给我一个错误吗?
-
它在 cmets 中,视觉效果在那里 @LawrenceCherone
-
这只是一种制作示例的方式,但它应该看起来像我们将类别作为键,然后是一个包含值的列表@LawrenceCherone