简体   繁体   中英

PHP - Create a multidimensional array

Is there any way to create this array from some existed arrays in 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
            )

    )

)

What I have tried

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

didnot bring me my expectation.

Beside that, what is the most effective way to get views/likes of an item. Should I use array or json object?

$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;
        }
    }
}

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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