我在下面提到了我的php数组对象,
$arr ='[
{
"id": 4667,
"brand": "Michelin",
"model": "Pilot Super Sport",
"width": "255",
"height": "35",
"rim": "19",
},
{
"id": 4668,
"brand": "Michelin",
"model": "Pilot Super Sport",
"width": "275",
"height": "35",
"rim": "19",
},
{
"id": 4669,
"brand": "Pirelli",
"model": "Zero",
"width": "255",
"height": "35",
"rim": "19",
},
{
"id": 4670,
"brand": "Pirelli",
"model": "Zero",
"width": "275",
"height": "35",
"rim": "19",
}]';
我想把数组分成前面和后面分开,就像下面这样基于宽度。
$front = '[
{
"id": 4667,
"brand": "Michelin",
"model": "Pilot Super Sport",
"width": "255",
"height": "35",
"rim": "19",
},
{
"id": 4669,
"brand": "Pirelli",
"model": "Zero",
"width": "255",
"height": "35",
"rim": "19",
}]';
$rear = '[
{
"id": 4668,
"brand": "Michelin",
"model": "Pilot Super Sport",
"width": "275",
"height": "35",
"rim": "19",
},
{
"id": 4670,
"brand": "Pirelli",
"model": "Zero",
"width": "275",
"height": "35",
"rim": "19",
}]';
php可以比较每个对象的宽度值并将它们分组,这是match。请建议。谢谢你的宝贵时间。
我认为你可以使用下面的代码:
$arr='[{
"id": 4667,
"brand": "Michelin",
"model": "Pilot Super Sport",
"width": "255",
"height": "35",
"rim": "19"
}, {
"id": 4668,
"brand": "Michelin",
"model": "Pilot Super Sport",
"width": "275",
"height": "35",
"rim": "19"
}, {
"id": 4669,
"brand": "Pirelli",
"model": "Zero",
"width": "255",
"height": "35",
"rim": "19"
}, {
"id": 4670,
"brand": "Pirelli",
"model": "Zero",
"width": "275",
"height": "35",
"rim": "19"
}]';
$front=[];
$rear=[];
foreach(json_decode($arr,true) as $key=>$val)
{
if($val['width']==255)
{
$front[]=$val;
}
else{
$rear[]=$val;
}
}
$front=json_encode($front);
$rear=json_encode($rear);
这是为我工作,但需要简化
$all = []; $front = []; $rear = [];
for($i=0; $i<count($arr); $i++){
array_push($all, $arr[$i]->width);
}
$filter = array_unique($all);
$max = max($filter);
$min = min($filter);
for($j=0; $j<count($arr); $j++){
if($arr[$j]->width == $max){
array_push($rear, $arr[$j]);
} else if($arr[$j]->width == $min){
array_push($front, $arr[$j]);
} else {
echo 'Not Match';
}
}
echo "<script>console.log(".json_encode($front).")</script>";
echo "<script>console.log(".json_encode($rear).")</script>";