Nike Yulistia Angreni Nike Yulistia Angreni - 4 months ago 12
PHP Question

Get Lower Number In each array value in PHP

i have array here

"data": [
{
"ohp_id": "40",
"parent_ohp_id": "",
"level": "1"
},
{
"ohp_id": "42",
"parent_ohp_id": "",
"level": "2"
},
{
"ohp_id": "45",
"parent_ohp_id": "",
"level": "5"
},
{
"ohp_id": "46",
"parent_ohp_id": "",
"level": "5"
},
{
"ohp_id": "47",
"parent_ohp_id": "",
"level": "5"
}


I need to compare each other array value and get lower number of
level
then get
ohp_id
of the lower level from each of them in PHP code. Here what i need to be:

"data": [
{
"ohp_id": "40",
"parent_ohp_id": "",
"level": "1"
},
{
"ohp_id": "42",
"parent_ohp_id": "40",
"level": "2"
},
{
"ohp_id": "45",
"parent_ohp_id": "42"
"level": "5"
},
{
"ohp_id": "46",
"parent_ohp_id": "42",
"level": "5"
},
{
"ohp_id": "47",
"parent_ohp_id": "42",
"level": "5"
}


I know it need looping, tried:

for ($i = 0; $i < count($arrPosition); $i++) {

$hasPosition->loadHas($orgId, $arrPosition[$i]);

if (!$hasPosition->id) {
$hasPosition->level=$arrLevel[$i];
$hasPosition->parent_ohp_id=<get ohp id from lower level>;
$hasPosition->ohp_id=$ohp_id;
$hasPosition->save();
} else {
if ($hasPosition->level!=$arrLevel[$i])
$hasPosition->level=$arrLevel[$i];
if ($hasPosition->seat!=$arrSeat[$i])
$hasPosition->seat=$arrSeat[$i];

$hasPosition->save(true);
}
}


But i don't know how to get
ohp_id
from lower level. Help me, thanks

Answer

Here's how you can get minimal object of one array:

$min = array_reduce($data, function($min, $ohp) {
    return (!$min || $ohp['level'] < $min['level']) ? $ohp : $min;
});
Comments