I mentioned my php array object following below,
$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",
}]';
I want to split array into front and rear separate like following below based on width.
$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",
}]';
It's there any way php can compare each object width value and group them which is match. please advise. thanks for your valuable time.
CodePudding user response:
I think you can use below code:
$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);
CodePudding user response:
This is works for me but need to simplify
$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>";