显示依赖于差异数组名称的数组成员 [英] showing array member dependent the name of difference array
本文介绍了显示依赖于差异数组名称的数组成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我由laravel创建了一个网站,我想显示类别和相关的产品名称.
I created a site by laravel and I want to show categories and relevant products names.
我有一个数组,就像这样
I have an array and like this
$category = [
'1' => 'cat1',
'2' => 'cat2'
];
$product = [
'0' => array(
'name' => 'product1',
'category_id' => '2'
),
'1' => array(
'name' => 'product2',
'category_id' => '2'
),
'2' => array(
'name' => 'product3',
'category_id' => '2'
),
'3' => array(
'name' => 'product4',
'category_id' => '1'
),
'4' => array(
'name' => 'product5',
'category_id' => '1'
),
'5' => array(
'name' => 'product6',
'category_id' => '2'
)];
我想这样显示
<h3>cat1</h3>
<p>product4</p>
<p>product5</p>
<hr>
<hr>
<h3>cat2</h3>
<p>product1</p>
<p>product2</p>
<p>product3</p>
<p>product6</p>
您必须知道我正在使用laravel,我想使用laravel来完成这项工作,但是您也可以使用PHP进行编码,我想我可以将其转换为laravel
You have to know I'm using laravel and I want doing this job with laravel but you also can coding with PHP, I think I can to convert it in laravel
推荐答案
您可以使用Laravel集合的 groupBy 用于您的用例.
You can make use of Laravel collections' groupBy for your use case.
在控制器文件中,按category_id
键进行分组,然后通过循环在刀片中呈现它们.
In your controller file, group by category_id
key and render them in your blade by looping.
控制器代码段:
public function someMethod(){
$category = [
'1' => 'cat1',
'2' => 'cat2'
];
$product = [
'0' => array(
'name' => 'product1',
'category_id' => '2'
),
'1' => array(
'name' => 'product2',
'category_id' => '2'
),
'2' => array(
'name' => 'product3',
'category_id' => '2'
),
'3' => array(
'name' => 'product4',
'category_id' => '1'
),
'4' => array(
'name' => 'product5',
'category_id' => '1'
),
'5' => array(
'name' => 'product6',
'category_id' => '2'
)];
$category_collection = collect($product)->groupBy('category_id')->toArray();
return view('your_blade_name',compact('category_collection','category'));
}
刀片片段:
@foreach($category_collection as $category_id => $data)
<h3>{{ $category[$category_id] }}</h3>
@foreach($data as $current_data)
<p>{{ $current_data['name'] }}</p>
@endforeach
<hr>
<hr>
@endforeach
这篇关于显示依赖于差异数组名称的数组成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文