([サイズ]は定義しません)のようにPHPで配列を定義すると、
$cart = array();
次のように単純に要素を追加しますか。
$cart[] = 13;
$cart[] = "foo";
$cart[] = obj;
PHPの配列にaddメソッドがありませんか?たとえば、cart.add(13)
?
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);
?>
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 = [];
$cart[] = 13;
$cart[] = "foo";
$cart[] = obj;
あなたの最初の選択肢は私にとって非常にうまくいきます。
$cart = array();
cart[] = 1:
$cart[] = 'foo':
$cart = 3;
$products_arr["passenger_details"]=array();
array_Push($products_arr["passenger_details"],array("Name"=>"Isuru Eshan","E-Mail"=>"[email protected]"));
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>";
}