【发布时间】:2018-11-14 08:03:28
【问题描述】:
我想达到什么目的?
"product_attributes": [
{
"title": "Color",
"records": [
{
"attribute_name": "black",
"mpr": "100"
},
{
"attribute_name": "green",
"mpr": "200"
}
]
},
{
"title": "RAM",
"records": [
{
"attribute_name": "16GB",
"mpr": "10"
}
]
},
{
"title": "RAM",///remove this whole obeject
"records": []
}
]
我尝试过的:我从数据库中获取整个属性,然后将其与产品属性进行比较并制作这种格式,现在问题是当我开始遍历所有属性的比较结果时,每次我的 if( ) 条件失败。
如何删除具有空记录数组的空对象并重新索引我的最终数组?
这是我的代码:
$allattributes = DB::table('product_attributes')->where('subcategory_id', $product->subcat_id)->get(['attribute_title']);
$valuesnew = DB::table('current_product_attribute_values')->where('product_id', $product->id)->get();
$emptybool=false;
// checking for empty attributes
if ($valuesnew->count() > 0) {
// first foreach for 3 value
foreach ($allattributes as $name) {
//echo $name->attribute_title;
$boo = false;
// 40 record loop
$records = array();
foreach ($valuesnew as $compare) {
// if attibute title are same
if ($compare->attribute_title == $name->attribute_title) {
if ($boo == false) {
$titledata = $name->attribute_title;
$holddata['title'] = $titledata;
$boo = true;
}
$records[] = array("attribute_name" => $compare->attribute_value, "mpr" => $compare->attribute_mrp);
}
}
$holddata['records'] = $records;
$final[] = $holddata;
}
} else {
$final = array();
}
我尝试过的:
foreach($final as $k=>$arr){
//$final=array_filter($arr,'count');
if(array_filter($arr,'count') || array_values(array_filter($arr))){
unset($arr[$i]);
}
$i++;
}
print_r($final);//failed
测试用例:
从产品所属的子类别中获取所有属性。
从产品属性表中获取所有产品属性
然后在找到相同的记录时将所有属性的标题与产品属性进行比较,我已将其放入数组中。所以我实现了color=>red,black这种结构而不是color=>red,color=>black
现在测试用例是当所有属性都有 4 个属性颜色、大小、内存、处理器和产品只有两种颜色和内存在这种情况下,我的循环给了我空记录,就像我想要的最后一个标题一样删除具有空记录的对象。
提前感谢:)
**新尝试:**
foreach($final as $k=>$arr){
foreach($arr as $key=>$value){
$count=count($value);
if($count==0){
echo '<pre>';
echo ' am empty object remove me ';
'<br>';
unset($arr[$index]);//failed how can i remove this whole object from the main array
}
}
【问题讨论】:
-
您还想使用查询生成器吗?如果您愿意接受建议,我认为编写模型是一种更好的方式
-
是的,如果您对此有任何建议,我也可以使用它,请分享
标签: php arrays laravel multidimensional-array