从变量名创建数组



im试图从变量名创建一个数组。我想从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});
?>

不要让树隐藏森林:

$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?)

变量变量符号期望 strings (文字或变量):

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

说,您的方法看起来像是制作无与伦比的代码的绝妙方法。为什么不带有已知名称的数组?

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

最新更新