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

木は森隠してはいけません:

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

がと言った:

$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表記は文字列(リテラルまたは変数)を見込んをあなたのアプローチは、維持不能なコードを生成する素晴らしい方法のように見えます。なぜ知られている名前の配列ですか?

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

ありがとうございます!答えのための最初の、そして提案のために! –

関連する問題