繁体   English   中英

Laravel 5在JSON文件中搜索并显示数据

[英]Laravel 5 search in a JSON file and show data

我有一个搜索引擎,可以提前输入。 我想要的是经过搜索并提交后,显示结果。 这带来了两个问题:首先,它返回一个空数组 ,其次, 它不允许我访问告诉我它不是对象的属性。

在控制器中,我使用collect()来允许我访问属性,但是它也不起作用,并且在任何地方。

public function store(Request $request)
{
    $url = 'storage/json/es/noticia.json';
    $datos = file_get_contents($url);
    $data = json_decode($datos, true);
    $data = collect($data)->where("title","LIKE","%{$request->texto}%")->all();

    return view('web.buscar.index', compact('data'));
}

如果我使用$data = collect($data)->all(); 我可以看到集合:

array:8 [▼
  0 => []
  1 => array:4 [▼
    "id" => 2
    "title" => "There is a title"
    "lead" => "There is a lead"
    "slug" => "there-is-a-title"
  ]
  2 => array:4 [▶]
  3 => array:4 [▶]
  4 => array:4 [▶]
  5 => array:4 [▶]
  6 => array:4 [▶]
  7 => array:4 [▶]

]

然后,如果我尝试:在视图中使用$value->title$value->title出现错误: 试图获取非object的属性“ title” 视图中我有:

{!! Form::open([
    'route' => 'buscar',
    'id' => 'buscar',
    'name' => 'buscar',
    'class' => 'buscador col-xs-12',
    'method' => 'POST',
    'accept-charset' => 'utf-8'
    ]) !!}

    <input id="texto" name="texto" class="input_buscador typetitulo" autocomplete="off" type="text"/>

    {!! HTML::image('images/web/icons/lupa.svg', '',  array('height' => '30', 'class' => 'boton_buscador', 'onclick' => 'document.buscar.submit()') ) !!}

{!! Form::close() !!}

@if(isset($data))
    @foreach($data as $value)
        <span>{{$value->title}}</span><br>
    @endforeach
@endif

如果我使用$data = collect($data)->pluck('title'); 在控制器和视图中,我没有将属性命名为'title' ,但这可以工作,但这不是我想要的,因为我也需要访问其他属性。 任何想法? 提前致谢!

失败是因为数组中的第一个数组没有任何值,所以您将获得未定义的索引,通过执行以下操作删除所有空数组

    public function store(Request $request)
{
    $url = 'storage/json/es/noticia.json';
    $datos = file_get_contents($url);
    $data = json_decode($datos, true);

    $data = array_filter($data);

    $data = collect($data)->where("title","LIKE","%{$request->texto}%")->all();
    return view('web.buscar.index', compact('data'));
}

或者您可以测试一下是否在foreach中

 @foreach($data as $value)
    <span>{{$value->title ?? ''}}</span><br>
@endforeach

然后,您可以使用过滤器搜索集合

    collect($data)->filter(function ($item) use ($request) {
        return $item->title == $request->texto;
    )

您可以使用stristr等将收益编辑为更细化

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM