使用回显和串联在 PHP 中构建已知变量名称

Build a known variable name in PHP with echo and 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 条记录。