在PHP中向子数组添加一个数组元素

3

我有

$statement = Array
(
    [0] => Array
        (
            [red] => 06-01-2012
            [green] => 436
            [blue] => MEDIA
            [black] => 2006
        )

    [1] => Array
        (
            [red] => 06-01-2012
            [green] => 430
            [blue] => MEDIA
            [black] => 2007
        )

);

我想通过像 $statement[1] 这样的东西向数组1中添加 [flex] => 1。我尝试过使用数组合并,但它们已经将数组0和1组合在一起。基本上,我想添加到最新的一个。


重复问题:https://dev59.com/7nE95IYBdhLWcg3wWMhQ,已有解决方案:https://dev59.com/O3A75IYBdhLWcg3wm6Uj。 - mickmackusa
2个回答

7

如果我理解正确的话,请尝试以下方法:

$statement[count($statement)-1]['flex'] = 1;

5
<?php
$statement = array(
    array(
            "red" => 06-01-2012,
            "green" => 436,
            "blue" => "MEDIA",
            "black" => 2006
        )

    ,array(
            "red" => 06-01-2012,
            "green" => 436,
            "blue" => "MEDIA",
            "black" => 2006
        )

);

echo "<pre>";
print_r($statement); //first

$statement[1]["flex"] = 1;

print_r($statement); //second
?>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接