我有像这样的php数组:
$categories = array (
"audio-video" => "Audio & Video",
"books" => "Books",
"vehicles" => "Vehicles",
"watches" => "Watches"
)
如何为其中的每个元素添加另一个值,使其最终结果如下:
$categories = array ( // For example. This isn't the right thing.
"US01" => "audio-video" => "Audio & Video",
"US02" => "books" => "Books",
"US03" => "vehicles" => "Vehicles",
"US04" => "watches" => "Watches"
)
这可能吗?我希望能够使用第一个键访问每个元素的其他值。因此US01
将为Audio & Video
或audio-video
。这可能用PHP吗?
答案 0 :(得分:1)
你做不到。您所能做的就是生成一个新的数组,如下所示:
$categories = array(
array(
"US01",
"audio-video",
"Audio & Video"
),
array(
"US02",
"books",
"Books"
)
);
或使用USxx
作为密钥:
$categories = array(
"US01" => array(
"audio-video",
"Audio & Video"
),
"US02" => array(
"books",
"Books"
),
);
答案 1 :(得分:1)
您可以创建一个数组数组:
$categories = array (
"US01" => array("name" => "Audio & Video", "alias" => "audio-video"),
"US02" => array("name" => "Books", "alias" => "books"),
);
然后访问它:
echo $categories['US01']['alias']; // audio-video
echo $categories['US01']['name']; // Audio & Video
echo $categories['US02']['alias']; // books
echo $categories['US02']['name']; // Books
答案 2 :(得分:1)
怎么样
$categories = array(
"US01" => array("audio-video", "Audio & Video"),
"US02" => array("books", "Books"),
"US03" => array("vehicles", "Vehicles"),
"US04" => array("watches", "Watches")
)
通过
访问$categories['US01'][0]; // audio-video
$categories['US01'][1]; // Audio & Video
答案 3 :(得分:0)
这应该有效:
$categories = array (
"audio-video" => "Audio & Video",
"books" => "Books",
"vehicles" => "Vehicles",
"watches" => "Watches"
);
$newCategories = Array();
$i = 1;
foreach ($categories as $key => $value) {
$index = "US" . ($i < 10) ? "0" . $i : $i;
$newCategorys[$index] = Array('slug'=>$categories[$key], 'value'=>$categories[$value]);
$i++;
}
所以你可以用
来达到目的$newCategories['US01']['slug'] // for "audio-video "
和
$newCategories['US01']['value'] // for "Audio & Video"
(未测试的)
答案 4 :(得分:0)
不,不是这样,但可以这样做:
$categories = array (
"US01" => array("audio-video" => "Audio & Video"),
"US02" => array("books" => "Books"),
"US03" => array("vehicles" => "Vehicles"),
"US04" => array("watches" => "Watches")
)
答案 5 :(得分:0)
如果需要,可以使用二维数组。
$category = array("US01" => array("audio-video" => "Audio & Video"),
"US02" => array("books" => "Books"),
"US03" => array("vehicles" => "Vehicles"),
"US04" => array("watches" => "Watches")
);