我想访问foreach循环之外的变量(数组)。当我在foreach循环中回显时,我得到了这个:
$path='http://localhost:8000/api/devices';
try {
$device= new Client();
$answer= $device->request('GET', $path);
$body = $answer->getBody();
$status = 'true';
$message = 'Data found!';
$final= json_decode($body);
foreach ($final as $res) {
$id = $res->clientId;
echo $id;
}
在循环之外我只得到数组的最后一项:Result outside foreachloop
$route='http://localhost:8000/api/devices';
try {
$device= new Client();
$answer= $client->request('GET', $answer);
$body = $answer->getBody();
$status = 'true';
$message = 'Data found!';
$final= json_decode($body);
foreach ($finala $res) {
$id = $res->clientId;
}
echo $id;
你这样做:
foreach ($data as $item) {
$id= $item->clientId;
}
echo $id;
因此,每次,您的最后一个$id
值都会被删除并获得新的当前id值。
如果你想要所有的id,试试这个:
// Create an array
$id_array = array();
foreach ($data as $item) {
// Add each id value in your array
$id_array[]= $item->clientId;
}
// Here you can display your array and see that you have all value
var_dump($id_array);
现在如果你想在foreach循环之后使用echo
(或使用)每个id,你可以这样做:
foreach($id_array as $my_id) {
echo $my_id;
}