我在下面提到了我的 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有什么方法可以比較每個物件的寬度值并將它們分組。請指教。感謝您的寶貴時間。
uj5u.com熱心網友回復:
我認為您可以使用以下代碼:
$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);
uj5u.com熱心網友回復:
這對我有用,但需要簡化
$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>";
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/339095.html
上一篇:C 輸出陣列函式
下一篇:無法排序或列印出陣列
