Answers:
array_push
您所描述的两种方法都可以。
$cart = array();
$cart[] = 13;
$cart[] = 14;
// etc
//Above is correct. but below one is for further understanding
$cart = array();
for($i=0;$i<=5;$i++){
$cart[] = $i;
}
echo "<pre>";
print_r($cart);
echo "</pre>";
是相同的:
<?php
$cart = array();
array_push($cart, 13);
array_push($cart, 14);
// Or
$cart = array();
array_push($cart, 13, 14);
?>
$cart[]=...
乍一看语法看起来像变量分配而不是隐式array_push?
最好不要使用array_push
而只是使用您的建议。这些功能只会增加开销。
//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';
$cart = array();
$cart[] = 11;
$cart[] = 15;
// etc
//Above is correct. but below one is for further understanding
$cart = array();
for($i = 0; $i <= 5; $i++){
$cart[] = $i;
//if you write $cart = [$i]; you will only take last $i value as first element in array.
}
echo "<pre>";
print_r($cart);
echo "</pre>";
$products_arr["passenger_details"]=array();
array_push($products_arr["passenger_details"],array("Name"=>"Isuru Eshan","E-Mail"=>"isuru.eshan@gmail.com"));
echo "<pre>";
echo json_encode($products_arr,JSON_PRETTY_PRINT);
echo "</pre>";
//OR
$countries = array();
$countries["DK"] = array("code"=>"DK","name"=>"Denmark","d_code"=>"+45");
$countries["DJ"] = array("code"=>"DJ","name"=>"Djibouti","d_code"=>"+253");
$countries["DM"] = array("code"=>"DM","name"=>"Dominica","d_code"=>"+1");
foreach ($countries as $country){
echo "<pre>";
echo print_r($country);
echo "</pre>";
}
$cart[] = 13
方法,不仅因为执行相同操作的字符更少,而且也不会增加函数调用的性能开销,而array_push()会造成这种情况。编辑:但是,很好的答案。实际上是相同的,并且大多数用途甚至都不会注意到性能差异,但是有助于了解这些细微差别。