如何从数组中删除不需要的值

问题描述 投票:0回答:3

有人知道为什么我要得到这种阵列吗?我只想要下面这部分。array ( 'name' => 'Westwood Residence', 'id' => 538, ),

 0 => 
  Common\Models\Property::__set_state(array(
     'connection' => 'mysql',
     'table' => NULL,
     'primaryKey' => 'id',
     'keyType' => 'int',
     'incrementing' => true,
     'with' => 
    array (
    ),
     'withCount' => 
    array (
    ),
     'perPage' => 15,
     'exists' => true,
     'wasRecentlyCreated' => false,
     'attributes' => 
    array (
      'name' => 'Westwood Residence',
      'id' => 538,
    ),
     'original' => 
    array (
      'name' => 'Westwood Residence',
      'id' => 538,
    ),
     'changes' => 
    array (
    ),
     'casts' => 
    array (
    ),
     'dates' => 
    array (
    ),
     'dateFormat' => NULL,
     'appends' => 
    array (
    ),
     'dispatchesEvents' => 
    array (
    ),
     'observables' => 
    array (
    ),
     'relations' => 
    array (
    ),
     'touches' => 
    array (
    ),
     'timestamps' => true,
     'hidden' => 
    array (
    ),
     'visible' => 
    array (
    ),
     'fillable' => 
    array (
    ),
     'guarded' => 
    array (
      0 => '*',
    ),
  )),

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

我得到了这个数组,希望您能理解我的问题。

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

            if($jsonData->cityID !==""){
                Log::info('city id found');
                foreach ($properties as $property){
                    if($property->city_id === $jsonData->cityID){
                            $filteredProperty[] = $property;
                    }
                }

            }
php arrays laravel foreach associative-array
3个回答
1
投票

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

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

0
投票

根据Laravel文档,您可以使用toArray()功能

toArray方法将集合转换为纯PHP数组。如果集合的值为Eloquent模型,则这些模型也将转换为数组。

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

Laravel -> Collection -> toArray


0
投票

[get()将返回一个laravel集合,因此请使用toArray()获得Array

也可以指定文件名来缩小数组的范围:

$properties = prop_model::select('name','id')
                ->where('status', '=', 'Active')
                ->where('propertylive', '=', 'Yes')
                ->get()
                ->toArray();
© www.soinside.com 2019 - 2024. All rights reserved.