How to add elements to an empty array in PHP?
如果我在PHP中定义一个数组,比如(我不定义它的大小):
1 |
我是否只需使用以下方法向它添加元素?
1 2 3 | $cart[] = 13; $cart[] ="foo"; $cart[] = obj; |
PHP中的数组是否没有add方法,例如
1 2 3 4 5 6 7 8 9 10 11 12 13 |
;< /代码>
相同:
1 2 3 4 5 6 7 8 9 | <?php $cart = array(); array_push($cart, 13); array_push($cart, 14); // Or $cart = array(); array_push($cart, 13, 14); ?> |
最好不要使用
1 2 3 4 5 6 7 8 9 10 11 12 13 | //We don't need to define the array, but in many cases it's the best solution. $cart = array(); //Automatic new integer key higher than the highest //existing integer key in the array, starts at 0. $cart[] = 13; $cart[] = 'text'; //Numeric key $cart[4] = $object; //Text key (assoc) $cart['key'] = 'test'; |
根据我的经验,当密钥不重要时,您的解决方案很好(最好):
1 2 3 4 | $cart = []; $cart[] = 13; $cart[] ="foo"; $cart[] = obj; |
你可以使用数组"推"。它将元素添加到数组的末尾,就像在堆栈中一样。
你也可以这样做:
1 |
记住,这个方法覆盖第一个数组,所以只有在确定的时候才使用!
1 | $arr1 = $arr1 + $arr2; |
(见源代码)
1 2 3 4 5 | $products_arr["passenger_details"]=array(); array_push($products_arr["passenger_details"],array("Name"=>"Isuru Eshan","E-Mail"=>"[email protected]")); echo"[cc lang="php"]"; echo json_encode($products_arr,JSON_PRETTY_PRINT); echo" |
;/或$countries=array();$countries["dk"]=数组("code"=>"dk","name"=>"丹麦","d_code"=>"+45");$countries["dj"]=数组("code"=>"dj","name"=>"djibouti","d_code"=>"+253");$countries["dm"]=数组("code"=>"dm","name"=>"Dominica","d_code"=>"+1");foreach($countries as$country){echo"
1 2 3 | "; echo print_r($country); echo" |
号";}< /代码>
你的第一个选择对我来说很好。
1 2 3 4 |
当我们希望元素添加为基于零的元素索引时,我想这也会起作用:
1 2 3 4 5 6 |
它叫做array_push:http://il.php.net/function.array-push