2017-02-21 44 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

谢谢!首先为答案,然后为建议! –