为什么只有一项显示在foreach循环之外?

时间:2018-07-05 14:10:50

标签: php laravel foreach guzzle

我想在foreach循环之外访问变量(数组)。当我在foreach循环内做回显时,我得到这个信息:

Reuslt inside foreach roop

public class MainViewModel : INotifyPropertyChanged
{
    private readonly Model Data;

    public MainViewModel()
    {
        Data = new Model();
        Data.PropertyChanged += Data_PropertyChanged;
    }

    private void Data_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        OnPropertyChanged("BoundTextProperty");
    }

    public string BoundTextProperty => Data.BoundTextProperty;

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

在循环之外,我仅得到数组的最后一项: Result outside foreachloop

$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;
    }

1 个答案:

答案 0 :(得分:1)

您正在这样做:

CSV.foreach(input_stops,
            encoding: 'iso-8859-1:utf-8',
            headers: true,
            header_converters: :symbol) do |row|
  p row[:stopid]
end

因此,每次,您的最后一个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); (或使用)每个id在foreach循环之后,您可以执行以下操作:

echo