繁体   English   中英

向PHP数组添加额外的键/值

[英]Adding an extra key / value to a PHP array

我有这样的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 & Videoaudio-video 这可能与php吗?

你不能。 您所能做的就是在内部生成一个新数组,如下所示:

$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"
    ),
);

您可以制作一个数组数组:

$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

怎么样

$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

这应该工作:

$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"

(未试)

不,不是这样,但是可以这样:

$categories = array (
    "US01" => array("audio-video" => "Audio & Video"),
    "US02" => array("books" => "Books"),
    "US03" => array("vehicles" => "Vehicles"),
    "US04" => array("watches" => "Watches")
)

如果需要,可以使用二维数组。

$category = array("US01" => array("audio-video" => "Audio & Video"),
    "US02" => array("books" => "Books"),
    "US03" => array("vehicles" => "Vehicles"),
    "US04" => array("watches" => "Watches")
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM