如何解决在PHP中使用echo和concatenation建立一个已知的变量名
在PHP中构建变量名有点麻烦。在下面的代码中,while循环不会产生值。代码的第二部分起作用。如果使用静态数字建立名称,则可以访问所有记录。例如,$ myresults1100 [id]有效,并提供了我的第1100个结果。如何使它与变量一起工作?我看过其他文章,但每个人似乎都想找到变量的名称。我知道这个名字,我只需要用正确的语法构建它即可。请告诉我我做错了。谢谢!
`enter code here`
<?php
$curl = curl_init();
curl_setopt_array($curl,[
CURLOPT_URL => "https://l4chsalter-alternative-me-crypto-
v1.p.rapidapi.com/v2/listings/",CURLOPT_RETURNTRANSFER => true,CURLOPT_FOLLOWLOCATION => true,CURLOPT_ENCODING => "",CURLOPT_MAXREDIRS => 10,CURLOPT_TIMEOUT => 30,CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,CURLOPT_CUSTOMREQUEST => "GET",CURLOPT_HTTPHEADER => [
"x-rapidapi-host: l4chsalter-alternative-me-crypto-v1.p.rapidapi.com","x-rapidapi-key:
],]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
$cleaned = $response;
$cleaned1 = str_replace('{',"",$cleaned);
$cleaned2 = str_replace('}',$cleaned1);
$cleaned3 = str_replace('[',$cleaned2);
$cleaned4 = str_replace(']',$cleaned3);
$cleaned5 = str_replace('"',$cleaned4);
$cleaned6 = str_replace(' ',$cleaned5);
# Removing some unique stuff from the start of the response
$mysearchstring = 'data: ';
$cleaned6=preg_replace('/\s+/','',$cleaned6);
$i=0;
#Turn the string into an array
$last_half = explode(',',$cleaned6);
foreach($last_half as $item){
list($k,$v) = explode(':',$item);
$result[$k] = $v;
${"myresults$i"} = $result;
${"result[name]myresults$i"} = $result;
$i++;
}
$mine = 1;
while($mine < 4){
echo "--------------------------------------------------------</br>";
echo "The id is "; echo ${"myresults$mine"}[id]; echo "</br>";
echo "The id is "; echo "$myresults . $mine[id]";echo "</br>";
echo "The name is "; echo "$myresults . $mine[name]";echo "</br>";
echo "The symbol is "; echo "$myresults . $mine[symbol]";echo "</br>";
echo "The website_slug is "; echo "$myresults .
mine[website_slug]";echo "</br>";
echo "-----------------------------------------------------</br>";
$mine++;
}
echo "-----------------------------------------------------</br>-";
echo "The id is " . $myresults1100[id];echo "</br>";
echo "The name is " . $myresults1100[name];echo "</br>";
echo "The symbol is " . $myresults1100[symbol];echo "</br>";
echo "The website_slug is " . $myresults1100[website_slug];echo "</br>";
echo "------------------------------------------------------</br>";
}
解决方法
echo "id is " . ${"myresults$i"}[id];
这是有效的语法。它使我可以构建变量名,而不必给它静态数代替i $。它必须在foreach循环内移动才能工作。使用此程序,我可以打印阵列中的所有1420条记录。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。