2017-02-21 51 views
0

林創建陣列試圖創建一個變量名的數組。我想從一個SQL表中的信息,並保持在一個數組的信息,但是我得到一個錯誤,說「不能用[]閱讀」。爲什麼?從變量名

<?php 
// SQL Selection CurrentProduct Attributes 
$sql = "SELECT * FROM $current_product_name"; 
$result = $conn->query($sql); 
while($row = $result->fetch_assoc()) { 
${current_product_name ._array[]} = $row; // add the row in to the array 
} 
${current_product_name ._length} = count({$current_product_name . _array}); 
?> 

回答

2

不要讓躲在樹森林:

$foo = []; // OK (create empty array with the PHP/5.4+ syntax) 
$foo[] = 10; // OK (append item to array) 
echo $foo[0]; // OK (read one item) 
echo $foo[]; // Error (what could it possibly mean?) 

variable variables符號預計(無論是文字或變量):

$current_product_name = 'Jimmy'; 
${$current_product_name . '_array'}[] = 33; 
var_dump($Jimmy_array); 
array(1) { 
    [0]=> 
    int(33) 
} 

據說,你的方法看起來像是一種產生不可維護代碼的好方法。爲什麼不使用已知名稱的數組?

$products[$current_product_name][] = $row; 
+0

謝謝!首先爲答案,然後爲建議! –