访问多维数组中的元素

问题描述 投票:0回答:2

我有一个动态生成的PHP多维数组如下:

Array (
    [uid_1] => Array (
        [sub_1] => Array (
            [sub_sub_1] => Array (
                [id1] => "val_1",
                [id2] => "val_2"
            )
        )
        [sub_2] => Array (
            [sub_sub_1] => Array (
                [id1] => "val_1",
                [id2] => "val_2"
            ),
            [sub_sub_2] => Array (
                [id3] => "val_3",
                [id4] => "val_4"
            )
        )
    )
)

数组要大得多,将包含多个 [uid]、[sub] 和 [sub_sub]。
请注意,虽然 [uid] 和 [sub] 是唯一的,但 [sub_sub] 不是唯一的。

是否可以在不使用循环且不知道 [uid_1] 和 [sub_2] 值的情况下将 [id5] => "val_5" 添加到 [sub_sub_1] 的所有实例?

php multidimensional-array
2个回答
0
投票

既然你提到了数组要大得多,可能需要循环。

    <?php
    $mainArray = array (
        "uid_1" => array (
            "sub_1" => array (
                "sub_sub_1" => array (
                    "id1" => "val_1",
                    "id2" => "val_2"
                )
                ),
            "sub_2" => array (
                "sub_sub_1" => array (
                    "id1" => "val_1",
                    "id2" => "val_2"
                ),
                "sub_sub_2" => array (
                    "id3" => "val_3",
                    "id4" => "val_4"
                )
            )
        )
    );

    echo "<pre>";
    print_r( $mainArray );
    echo "</pre>";



    foreach($mainArray["uid_1"] as $key=>$val){
        
        //$val (Arrays with index 'sub_1', 'sub_2' etc.)
        //Get array with index 'sub_sub_1' & Assign a New Value with key `id5`.

        $mainArray["uid_1"][$key]['sub_sub_1']["id5"] = "val_5";


    }

    echo "<pre>";
    print_r( $mainArray );
    echo "</pre>";
    ?>

0
投票

尝试以下代码。

<?php
$mainArray = array(
    "uid_1" => array(
        "sub_1" => array(
            "sub_sub_1" => array(
                "id1" => "val_1",
                "id2" => "val_2"
            )
        ),
        "sub_2" => array(
            "sub_sub_1" => array(
                "id1" => "val_1",
                "id2" => "val_2"
            ),
            "sub_sub_2" => array(
                "id3" => "val_3",
                "id4" => "val_4"
            )
        )
    )
);

echo "<pre>";
print_r($mainArray);
echo "</pre>";

foreach ($mainArray["uid_1"] as $key => $val) {

    // Check if 'sub_sub_1' exists before trying to access it
    if (isset($mainArray["uid_1"][$key]['sub_sub_1'])) {
        // Get array with index 'sub_sub_1' & Assign a New Value with key `id5`.
        $mainArray["uid_1"][$key]['sub_sub_1']["id5"] = "val_5";
    }
}

echo "<pre>";
print_r($mainArray);
echo "</pre>";
?>
© www.soinside.com 2019 - 2024. All rights reserved.