添加到多维数组

时间:2014-06-17 22:32:30

标签: php arrays wordpress multidimensional-array foreach

这是我的代码:

$get_access_keys_from_wp = get_user_meta( $user_id, '_tdv_volunteer_positions' );
$new_access_keys = array();    

if ( $get_access_keys_from_wp ) {
            echo "This user is signed up for other positions.";

            $current_access_keys = $get_access_keys_from_wp;

            foreach($current_access_keys as $key => $value) {
                $new_access_keys[] = $value;
            }
            //$new_access_keys[] = $position_post_id;
            $new_access_keys[] = array('position_id' => $position_post_id, 'volunteer_first_name' => $first_name, 'volunteer_last_name' => $last_name);

        } else {
            echo "This user is not signed up for any positions.";

            //$new_access_keys[] = $position_post_id;
            $new_access_keys[] = array('position_id' => $position_post_id, 'volunteer_first_name' => $first_name, 'volunteer_last_name' => $last_name);

        }

最初,我得到以下内容:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [position_id] => 67
                    [volunteer_first_name] => Mike
                    [volunteer_last_name] => Jackson
                )

        )

)

那很好......我想要这样。但正如您可以通过上面的逻辑看到的那样,我需要能够遍历数组(如果它已经存在),并添加它以使它看起来如下所示:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [position_id] => 67
                    [volunteer_first_name] => Mike
                    [volunteer_last_name] => Jackson
                )
            [1] => Array
                (
                    [position_id] => 68
                    [volunteer_first_name] => Mike
                    [volunteer_last_name] => Jackson
                )

        )

)

但相反,我得到的结果如下:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => Array
                        (
                            [position_id] => 67
                            [volunteer_first_name] => Mike
                            [volunteer_last_name] => Jackson
                        )

                )

            [1] => Array
                (
                    [position_id] => 68
                    [volunteer_first_name] => Mike
                    [volunteer_last_name] => Jackson
                )

        )

)

1 个答案:

答案 0 :(得分:2)

在添加现有值时,您似乎需要更深入1级。尝试替换

foreach($current_access_keys as $key => $value) {
    $new_access_keys[] = $value;
}

foreach($current_access_keys as $key => $value) {
    $new_access_keys[] = $value[0];
}

或者如果现有数组包含多于1个元素

foreach($current_access_keys as $key => $value) {
    $new_access_keys = array_merge($new_access_keys,$value);
}