【问题标题】:how to remove unwanted values form array如何从数组中删除不需要的值
【发布时间】:2020-06-25 09:32:12
【问题描述】:

有人知道我为什么要得到这种数组吗?我只想要下面的部分。我需要从中删除那些 mysql 连接和其他不需要的数组。

array (
  'name' => 'Westwood',
  'id' => 538,
),
 0 => 
  Common\Models\Property::__set_state(array(
     'connection' => 'mysql',
     'table' => NULL,
     'primaryKey' => 'id',
     'keyType' => 'int',
     'incrementing' => true,
     'with' => 
    array (
    ),
     'perPage' => 15,
     'exists' => true,
     'wasRecentlyCreated' => false,
     'attributes' => 
    array (
      'name' => 'Westwood',
      'id' => 538,
    ),
     'guarded' => 
    array (
      0 => '*',
    ),
  )),

下面的代码显示了我为获取该数组所做的工作。当我Log::info($results);

我得到了那个数组希望你理解我的问题。

$properties = model::where('status', '=', 'Active')
                ->get();

if($jsonData->city !== "") {
    foreach ($properties as $property) {
        if($property->city === $jsonData->city) {
            $results[] = $property;
        }
    }
}

【问题讨论】:

    标签: php arrays laravel foreach associative-array


    【解决方案1】:

    基于get() manual

    get 方法返回一个 Illuminate\Support\Collection,其中包含 results 其中每个结果都是 PHP stdClass 对象的一个​​实例。 您可以通过访问列来访问每一列的值 对象的属性

    它将返回一个 laravel 集合。

    所以使用toArray() 来获取数组

    toArray 方法将集合转换为普通的 PHP 数组。如果 该集合的值是 Eloquent 模型,模型也将是 转换为数组

    同时指定文件名来缩小你的数组范围:

    $properties = prop_model::select('name','id')
                    ->where(['status', '=', 'Active'],['propertylive', '=', 'Yes'])
                    ->get()
                    ->toArray();
    

    参考:How to Create Multiple Where Clause Query Using Laravel Eloquent?

    【讨论】:

      【解决方案2】:

      get() 函数返回集合。因此,根据 Laravel 文档,您可以使用 toArray() 函数

      toArray 方法将集合转换为普通的 PHP 数组。如果集合的值是 Eloquent 模型,模型也会被转换为数组。

      $properties = prop_model::where('status', '=', 'Active')
                      ->where('propertylive', '=', 'Yes')
                      ->get()
                      ->toArray();
      

      Laravel -> Collection -> toArray

      【讨论】:

        【解决方案3】:

        当你使用get()时,它会返回一个laravel集合,而不是一个数组,如果你想要一个数组,你可以使用toArray()它看起来像这样:

        $properties = prop_model::where('status', '=', 'Active')
                        ->where('propertylive', '=', 'Yes')
                        ->get()
                        ->toArray();
        

        【讨论】:

        • 在 foreach 内部我有数组 ($filteredProperty[] = $property;),该数组给了我上面的数组。我想从数组中删除那些 mysql 连接值。你知道怎么做吗
        • 正如@Gamopo 在他的回答中解释的那样,您应该在调用get() 后使用toArray() 方法。这会将结果从集合对象(如 Laravel 文档中所述)转换为您需要的关联数组。 +1 OP
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-29
        • 2013-04-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多