laravel 将元素添加到数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21783945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:02:30  来源:igfitidea点击:

Adding elements to array?

laravellaravel-4

提问by panthro

How can I add more than one element to my keyed array?

如何将多个元素添加到我的键控数组中?

array_add($myArray, 'key', 'a');
array_add($myArray, 'key-2', 'b');

Is there a better way?

有没有更好的办法?

回答by Antonio Carlos Ribeiro

I prefer:

我更喜欢:

$myArray['key'] = 'a';
$myArray['key-2'] = 'b';

But this is not really better, because you're not adding more than one in a single command.

但这并不是更好,因为您不会在单个命令中添加多个。

And if you really need to add multiple, you can always create a helper:

如果你真的需要添加多个,你总是可以创建一个助手:

function array_add_multiple($array, $items)
{
    foreach($items as $key => $value)   
    {
        $array = array_add($items, $key, $value);
    }

    return $array;
}

And use it as

并将其用作

$array = array_add_multiple($array, ['key' => 'a', 'key-2' => 'b']);

or, if you're not using PHP 5.4:

或者,如果您没有使用 PHP 5.4:

$array = array_add_multiple($array, array('key' => 'a', 'key-2' => 'b'));

回答by The Alpha

There is no need for any other custom function because in PHPthere is a built-in function for this and it's array_mergeand you can use it like this:

不需要任何其他自定义函数,因为它PHP有一个内置函数,它是array_merge,您可以像这样使用它:

$myArray = array('one' => 'TheOne', 'two' => 'TheTwo');
$array = array_merge($myArray, array('three' => 'TheThree', 'four' => 'TheFour'));

print_r($array);

Output:

输出:

Array
(
    [one] => TheOne
    [two] => TheTwo
    [three] => TheThree
    [four] => TheFour
)

You can also use this:

你也可以使用这个:

$myArray1 = array('one' => 'TheOne', 'two' => 'TheTwo');
$myArray2 = array('three' => 'TheThree', 'four' => 'TheFour');;

$array = $myArray1 + $myArray2;
print_r($array);

Output:

输出:

Array
(
    [one] => TheOne
    [two] => TheTwo
    [three] => TheThree
    [four] => TheFour
)

回答by Miroslav Trninic

My custom "on the fly" method:

我的自定义“即时”方法:

function add_to_array($key_value)
    {
        $arr = [];
        foreach ($key_value as $key => $value) {
            $arr[] = [$key=>$value];
        }
        return $arr;
    }
    dd(add_to_array(["hello"=>"from this array","and"=>"one more   time","what"=>"do you think?"]));