PHP - 创建一个多维数组

时间:2014-03-02 17:23:18

标签: php arrays multidimensional-array

有没有办法从PHP中的一些现有数组创建这个数组

Array(
[in-door] => Array
    (
        [tv] => Array
            (
                [views] => 123
                [likes] => 234
                [comments] => 345
                [shares] => 456
            )

        [sofa] => Array
            (
                [views] => 567
                [likes] => 789
                [comments] => 890
                [shares] => 901
            )
    ),
[out-door] => Array
        (
        [chair] => Array
                (
                    [views] => 109
                    [likes] => 98
                    [comments] => 987
                    [shares] => 876
                )

        [bench] => Array
            (
                [views] => 765
                [likes] => 654
                [comments] => 543
                [shares] => 432
            )

    )

)

我尝试了什么

$list_categories = array("in-door");
$list_items = array(array("tv", "sofa"));
$list_items_info = array(array(array(
         "views" => 123,
         "likes" => 234,
         "comments" => 345,
         "shares" => 456
          ),
    array(
         "views" => 123,
         "likes" => 234,
         "comments" => 345,
         "shares" => 456
         )
            ));
        print_r(array_combine($list_categories, array_combine($list_items, $list_items_info)));

没有给我带来期待。

除此之外,获取项目的观看/喜欢的最有效方法是什么。我应该使用数组还是json对象?

1 个答案:

答案 0 :(得分:0)

$list_categories = array("in-door");
$list_items = array("tv", "sofa");
$list_items_info = array(
    "views" => 123,
    "likes" => 234,
    "comments" => 345,
    "shares" => 456
);

$array = array();

foreach ($list_categories as $cat) {
    foreach ($list_items as $item) {
        foreach ($list_items_info as $itemname => $iteminfo) {
            $array[$cat][$item][$itemname] = $iteminfo;
        }
    }
}

输出:

Array
(
    [in-door] => Array
        (
            [tv] => Array
                (
                    [views] => 123
                    [likes] => 234
                    [comments] => 345
                    [shares] => 456
                )

            [sofa] => Array
                (
                    [views] => 123
                    [likes] => 234
                    [comments] => 345
                    [shares] => 456
                )

        )

)

Online demo