【问题标题】:Searching in cache data gives array first index 1在缓存数据中搜索给数组第一个索引 1
【发布时间】:2019-11-09 20:48:50
【问题描述】:
$this->getCachedCategories();
//Above code Stores the data in cache for future use. So, it goes to the database only 
//one time and next time pick the data from cache. So far everything is good.

//I have a search criteria which is in the form of array. I filter above cache data based 
//upon the search criteria and gets the data.
foreach ($userInputsForFilter as $key => $value) {
    $this->Categories = $this->Categories->where($key, $value);
}

这是屏幕截图。如果您注意到检索到的数据的第一个索引是 1 而不是 0。实际上第二条记录是在过滤缓存数据后出现的。

您能否解释一下为什么在搜索缓存数据时会出现这种情况?转到数据库时不会发生这种情况。

数组到 JSON 代码

$CategoryResponse = $this->iCategory->All([], []);
return \Response::json($CategoryResponse, 200);

【问题讨论】:

  • 在将Collection 转换为 JSON 时会发生这种情况;如果 ID 用于索引数组(关联的,1 => ... 而不是 0 => ...),那么它会将其视为对象而不是数组。你能把$this->Categories转换成JSON的代码贴出来吗?
  • 酷;试试return \Response::json(array_values($CategoryResponse->toArray()), 200);;应该将 Collection 转换为数组,然后重新索引(将关联转换为基于 0 的索引数组)。

标签: php laravel laravel-5 laravel-5.7 laravel-5.8


【解决方案1】:

Laravel 的 Collections 和 PHP 中的一般数组可以是关联的,这意味着第一个索引不一定是 0。当通过 Response::json()return response->json() 转换为 JSON 时,它可以是在 JS 中被视为 object 而不是数组。要处理这个问题,请将Collection 转换为数组,并通过PHP 的array_values() 函数更改为indexed

$CategoryResponse = $this->iCategory->All([], []);
return response()->json(array_values($CategoryResponse->toArray()), 200);
// Older Laravel syntax
// return \Response::json(array_values($CategoryResponse->toArray()), 200);

在 JSON 响应中,它应该正确显示为以 0 作为第一个索引的数组。

【讨论】:

    猜你喜欢
    • 2013-02-14
    • 2015-07-09
    • 1970-01-01
    • 2022-07-21
    • 2014-02-18
    • 1970-01-01
    • 2012-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多