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

고맙습니다! 먼저 대답을위한 다음 제안을 위해! –

관련 문제