在数组中添加元素的其他方法?

时间:2016-10-31 17:38:45

标签: php syntax

$a = ['foo' => 'bar'];

如果我想在这个数组中添加新元素,我通常会写这个

$a['foo2'] = 'bar2';
$a['foo3'] = 'bar3';
$a['foo4'] = 'bar4';

是否有其他语法,所以我可以添加这样的元素而不覆盖$a

$a =    [   'foo2' => 'bar2',
            'foo3' => 'bar3',
            'foo4' => 'bar4'];

5 个答案:

答案 0 :(得分:3)

您也可以这样做:

$arr1 = array('foo2' => 'bar2');
$arr2 = array('foo3' => 'bar3');
$arr3 = $arr1 + $arr2;

答案 1 :(得分:1)

您可以使用array_merge将数组添加到另一个数组的末尾。

$a = array_merge($a, $b); 

其中$b是:

$b =    [   'foo2' => 'bar2',
            'foo3' => 'bar3',
            'foo4' => 'bar4'];

答案 2 :(得分:0)

或者只是这样做:

$a = ['foo' => 'bar'];
$a = array_merge([$a,'foo2' => 'bar2',
            'foo3' => 'bar3',
            'foo4' => 'bar4'];

将返回你想要的东西。

答案 3 :(得分:-2)

这个怎么样? 我认为将元素添加到数组中是最简单的

<?php
 $cart = [];
//to add one
 array_push($cart, 13); 
 // to add multiple
 array_push($cart, 13,14,15); 

?>

答案 4 :(得分:-2)

  

您可以为此创建一个简单的函数:

<?php

    /**
     * @param $mainArray => THE ARRAY TO WHICH OTHER ELEMENTS (INCL. ARRAYS/OBJECTS) SHOULD BE ADDED
     * @param $data      => A KEY-VALUE PAIR ARRAY OR A NORMAL STRING/NUMBER
     * @return array
     */
    function arrayAdd(&$mainArray, $data){
        if(is_array($data)){
            foreach($data as $k=>$v){
                $mainArray[$k]  = $v;
            }
        }else if(is_string($data)){
            $mainArray[]        = $data;
        }
        return $mainArray;
    }

    // CREATE A OBJECT (TO SHOW IT COULD ALSO HANDLE THAT AS WELL)
    $obj    = new stdClass();
    $obj->name  = 'Some Name';
    $obj->tel   = '+1 202 532 00 00 00';

    // THE MAIN ARRAY TO WHICH OTHER ELEMENTS SHOULD BE ADDED 
    $main   = ['foo1' => 'bar1', 'foo2' => 'bar2'];

    // A COLLECTION OF DATA TO ADD TO $main
    $data   = [
        'one'   => 'Un',
        'two'   => 'Deux',
        'three' => 'Trois',
        'four'  => 'Quart',
        'obj'   => $obj,
    ];

    // CALL THE FUNCTION AND PASS THE PARAMETERS
    var_dump( arrayAdd($main, $data) );

    // YIELDS:: 
    array (size=7)
      'foo1' => string 'bar1' (length=4)
      'foo2' => string 'bar2' (length=4)
      'one' => string 'Un' (length=2)
      'two' => string 'Deux' (length=4)
      'three' => string 'Trois' (length=5)
      'four' => string 'Quart' (length=5)
      'obj' => 
        object(stdClass)[1]
          public 'name' => string 'Some Name' (length=9)
          public 'tel' => string '+1 202 532 00 00 00' (length=19)