$productDetail['product']['id']='1324652';
$variable = "productDetail['product']['id']";
如何在php中使用「$ variable」打印「$ productDetail ['product'] ['id']」的值?如何通過變量的值打印數組值?
$productDetail['product']['id']='1324652';
$variable = "productDetail['product']['id']";
如何在php中使用「$ variable」打印「$ productDetail ['product'] ['id']」的值?如何通過變量的值打印數組值?
不是好辦法,JUSE給大家一個參考
$productDetail['product']['id']='1111';
$productDetail['product']['idd']['id']='2222';
$variable = "productDetail['product']['idd']['id']";
$variable_new = parse_variable($variable);
$re = $$variable_new[0];
if(count($variable_new) > 1){
// loop $variable_new to get next data, one by one
\t for($i = 1; $i < count($variable_new); $i++){
\t \t $re = $re[$variable_new[$i]];
\t }
}
var_dump($re);exit;
// parse variable to array
function parse_variable($variable){
\t // return $variable if there no [
\t if(!strpos($variable, '[')){
\t \t return array(0 => $variable);
\t }
\t // parse variable to array
\t $variables = explode('[', $variable);
\t $new_variables = '';
\t foreach($variables as $variable){
\t \t $variable = str_ireplace("'", '', $variable);
\t \t $variable = str_ireplace("]", '', $variable);
\t \t $new_variables[] = $variable;
\t }
\t return $new_variables;
}
謝謝suibber,這是我真正想要的完美。但字符串輸入是動態的,來自用戶輸入,所以我如何使它像使用動態可能輸入「productDetail ['product'] ['id']」或只是「productDetail ['product']」或「productDetail [''產品'] ['id'] ['id']「 –
我編輯了我的答案,您可以循環用戶輸入以獲取數據 – suibber
你的意思是數組元素的值賦給'$ variable'?這只是'$ variable = $ productDetail ['product'] ['id'];打印$變量;' – SaschaM78
它與我們在下面的例子中使用$$ Lke相同** $ a ='name'; $$ a =「Paul」; echo $ name; 輸出是Paul ** –
對不起,您的評論不符合您的初始問題,您能否更好地解釋您真正嘗試實現的目標? – SaschaM78