Moving an element with specific value to the end of dimensional array - php

Original Array
$sonuc['rec'][0]['m_unseen'] = 1;
$sonuc['rec'][0]['user_id'] = 234;
$sonuc['rec'][0]['id'] = 133;
$sonuc['rec'][0]['last_updated'] = date();
$sonuc['rec'][0]['user']['unseen'] = 0;
$sonuc['rec'][0]['user']['id'] = 234;
$sonuc['rec'][1]['m_unseen'] = 0;
$sonuc['rec'][1]['user_id'] = 234;
$sonuc['rec'][1]['id'] = 134;
$sonuc['rec'][1]['last_updated'] = date();
$sonuc['rec'][1]['user']['unseen'] = 0;
$sonuc['rec'][1]['user']['id'] = 234;
$sonuc['rec'][2]['m_unseen'] = 0;
$sonuc['rec'][2]['user_id'] = 234;
$sonuc['rec'][2]['id'] = 135;
$sonuc['rec'][2]['last_updated'] = date();
$sonuc['rec'][2]['user']['unseen'] = 0;
$sonuc['rec'][2]['user']['id'] = 234;
$sonuc['rec'][3]['m_unseen'] = 1;
$sonuc['rec'][3]['user_id'] = 234;
$sonuc['rec'][3]['id'] = 136;
$sonuc['rec'][3]['last_updated'] = date();
$sonuc['rec'][3]['user']['unseen'] = 0;
$sonuc['rec'][3]['user']['id'] = 234;
Expected Result
$sonuc['rec'][0]['m_unseen'] = 1;
$sonuc['rec'][0]['user_id'] = 234;
$sonuc['rec'][0]['id'] = 133;
$sonuc['rec'][0]['last_updated'] = date();
$sonuc['rec'][0]['user']['unseen'] = 0;
$sonuc['rec'][0]['user']['id'] = 234;
$sonuc['rec'][1]['m_unseen'] = 1;
$sonuc['rec'][1]['user_id'] = 234;
$sonuc['rec'][1]['id'] = 136;
$sonuc['rec'][1]['last_updated'] = date();
$sonuc['rec'][1]['user']['unseen'] = 0;
$sonuc['rec'][1]['user']['id'] = 234;
$sonuc['rec'][2]['m_unseen'] = 0;
$sonuc['rec'][2]['user_id'] = 234;
$sonuc['rec'][2]['id'] = 134;
$sonuc['rec'][2]['last_updated'] = date();
$sonuc['rec'][2]['user']['unseen'] = 0;
$sonuc['rec'][2]['user']['id'] = 234;
$sonuc['rec'][3]['m_unseen'] = 0;
$sonuc['rec'][3]['user_id'] = 234;
$sonuc['rec'][3]['id'] = 135;
$sonuc['rec'][3]['last_updated'] = date();
$sonuc['rec'][3]['user']['unseen'] = 0;
$sonuc['rec'][3]['user']['id'] = 234;
I am trying to move all elements with m_unseen value is 0 to the end of the array.
I tried but couldn't get the expected result
function moveElement(&$array, $a, $b) {
$out = array_splice($array, $a, 1);
array_splice($array, $b, 0, $out);
}
$keys = array_keys(array_column($sonuc['rec'], 'm_unseen'), 0);
foreach ($keys as $key) {
moveElement($sonuc['rec'], $key, $say);
}
Any idea?

You could use the usort function with a custom callback to do the trick
This function takes two argument, the array ( passed by reference ) and a callback with two element. You compare the two element in the callback.
Here, we've simply subtract one "m_unseen" to the other since they are numbers. If it was another type, we would need to return a positive or negative integer, or 0 if they are equals, since that's what the usort function expect.
<?php
$sonuc = array();
$sonuc['rec'][0]['m_unseen'] = 1;
$sonuc['rec'][0]['user_id'] = 234;
$sonuc['rec'][0]['id'] = 133;
$sonuc['rec'][0]['last_updated'] = date(1584796457);
$sonuc['rec'][0]['user']['unseen'] = 0;
$sonuc['rec'][0]['user']['id'] = 234;
$sonuc['rec'][1]['m_unseen'] = 0;
$sonuc['rec'][1]['user_id'] = 234;
$sonuc['rec'][1]['id'] = 134;
$sonuc['rec'][1]['last_updated'] = date(1584796457);
$sonuc['rec'][1]['user']['unseen'] = 0;
$sonuc['rec'][1]['user']['id'] = 234;
$sonuc['rec'][2]['m_unseen'] = 0;
$sonuc['rec'][2]['user_id'] = 234;
$sonuc['rec'][2]['id'] = 135;
$sonuc['rec'][2]['last_updated'] = date(1584796457);
$sonuc['rec'][2]['user']['unseen'] = 0;
$sonuc['rec'][2]['user']['id'] = 234;
$sonuc['rec'][3]['m_unseen'] = 1;
$sonuc['rec'][3]['user_id'] = 234;
$sonuc['rec'][3]['id'] = 136;
$sonuc['rec'][3]['last_updated'] = date(1584796457);
$sonuc['rec'][3]['user']['unseen'] = 0;
$sonuc['rec'][3]['user']['id'] = 234;
usort($sonuc['rec'], function($a, $b) {
// switching the variable here would order the array ASC rather than DSC.
return $b['m_unseen'] - $a['m_unseen'];
});
var_dump($sonuc);
Here is a sandbox for you to test it out

usort with custom sort function is enough:
usort($sonuc['rec'], function($a, $b) {
return 1 == $a['m_unseen'] ? -1 : 1;
});

You can simply move the m_unseen with non zero values to the front, swapping zero values to the back with the help of a pointer variable.
<?php
$ptr = 0;
foreach($sonuc['rec'] as $key => $value){
if($value['m_unseen'] != 0){
$temp = $sonuc['rec'][$ptr];
$sonuc['rec'][$ptr++] = $value;
$sonuc['rec'][$key] = $temp;
}
}
Demo: https://3v4l.org/o1c5R

Related

Laravel controller won't pass parameter to service

so i made this input view which input some data, and then some services to process the data, these services are being called from the controller, the problem is when i try to call this particular function SUPMPFunc($index, $loop, $length) the controller seems to be not passing the arguments to the service.
This is the too few arguments error is get:
Controller:
<?php
class supmpController extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
public function Store(Request $request)
{
$medInput = new MedInput();
$deviceId = $medInput->MedInput();
$toolsInput = new ToolsInput();
$toolsRes = $toolsInput->ToolsInput(request("toolsIndex"));
$toolsfunctionInput = new ToolsFunctionInput();
$functionality = $toolsfunctionInput->ToolsFunctionInput(request("checkIndex"));
$temperature = new TempFunc();
$humidity = new HumidFUnc();
$condition = array(
$temperature->TempFunc(),
$humidity->HumidFUnc(),
);
$electricity = new Electricityinput();
$elInput = $electricity->ElectricityInput(request("electricIndex"));
$index = request("tablesupmpindex");
$loop = request("loopVal");
$length = request("supmpLength");
$SUPMP = new SUPMPFunc();
$result = $SUPMP->SUPMPFunc($index, $loop, $length);
$analysis = new AnalysisFunc();
$texttoShow = $analysis->AnalysisFunc();
$data = array (
array($deviceId, $texttoShow, $toolsRes, request("loopVal")), //0
$condition, //1
$functionality,//2
$elInput, //3
$result[0], //4
$result[1], //5
$result[2], //6
$result[3], //7
$result[4], //8
$result[5], //9
$result[6], //10
);
return view('laporan', ['data' => $data]);
}
}
Service:
<?php
class SUPMPFunc
{
public function SUPMPFunc($index, $loop, $length)
{
$Avg = new AvgFunc();
$TINV = new TINVFunc();
$round = new RoundFunc();
$stdev = new StdevFunc();
$budget = new BudgetFunc();
$drift = new DriftFunc();
$driftres = $drift->Drift1895040();
$medInput = new MedInput();
$deviceId = $medInput->MedInput();
$resolution = $deviceId[6];
///////////////////////////////////////////////////////////////////////////////
// everything below is related to calibration value
$settingsArray = [];
$valueArray = [];
for($i = 0; $i <= $length; $i++)
{
array_push($settingsArray, request("table".$index."setVal".$i));
}
$A1 = request('inVal_A-1');
$B1 = request('inVal_B-1');
$C1 = request('inVal_C-1');
$D1 = request('inVal_D-1');
$E1 = request('inVal_E-1');
$F1 = request('inVal_F-1');
$G1 = request('inVal_G-1');
$A2 = request('inVal_A-2');
$B2 = request('inVal_B-2');
$C2 = request('inVal_C-2');
$D2 = request('inVal_D-2');
$E2 = request('inVal_E-2');
$F2 = request('inVal_F-2');
$G2 = request('inVal_G-2');
$A3 = request('inVal_A-3');
$B3 = request('inVal_B-3');
$C3 = request('inVal_C-3');
$D3 = request('inVal_D-3');
$E3 = request('inVal_E-3');
$F3 = request('inVal_F-3');
$G3 = request('inVal_G-3');
$A4 = request('inVal_A-4');
$B4 = request('inVal_B-4');
$C4 = request('inVal_C-4');
$D4 = request('inVal_D-4');
$E4 = request('inVal_E-4');
$F4 = request('inVal_F-4');
$G4 = request('inVal_G-4');
$A5 = request('inVal_A-5');
$B5 = request('inVal_B-5');
$C5 = request('inVal_C-5');
$D5 = request('inVal_D-5');
$E5 = request('inVal_E-5');
$F5 = request('inVal_F-5');
$G5 = request('inVal_G-5');
$A6 = request('inVal_A-6');
$B6 = request('inVal_B-6');
$C6 = request('inVal_C-6');
$D6 = request('inVal_D-6');
$E6 = request('inVal_E-6');
$F6 = request('inVal_F-6');
$G6 = request('inVal_G-6');
$A7 = request('inVal_A-7');
$B7 = request('inVal_B-7');
$C7 = request('inVal_C-7');
$D7 = request('inVal_D-7');
$E7 = request('inVal_E-7');
$F7 = request('inVal_F-7');
$G7 = request('inVal_G-7');
$Aval = array(-$A1, -$A2, -$A3, -$A4, -$A5, -$A6, -$A7);
$Bval = array(-$B1, -$B2, -$B3, -$B4, -$B5, -$B6, -$B7);
$Dval = array(-$D1, -$D2, -$D3, -$D4, -$D5, -$D6, -$D7);
$Fval = array(-$F1, -$F2, -$F3, -$F4, -$F5, -$F6, -$F7);
$Cval = array(-$C1, -$C2, -$C3, -$C4, -$C5, -$C6, -$C7);
$Eval = array(-$E1, -$E2, -$E3, -$E4, -$E5, -$E6, -$E7);
$Gval = array(-$G1, -$G2, -$G3, -$G4, -$G5, -$G6, -$G7);
$koreksiStd = array(
array(0.0, 0.6, 0.7, 1.0, 0.9, 1.4, 1.3), //koreksistdUp
array(0.0, 0.7, 0.8, 1.1, 1.1, 1.7, 1.7), //koreksi tdDn
array(0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5), //Usertifikat up
array(0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5) //Usertifikat dn
);
$usertifikat = 0.5;
for($i = 0; $i < count($koreksiStd[0]); $i++ )
{
$Bval[$i] = $Bval[$i] + $koreksiStd[0][$i];
$Dval[$i] = $Dval[$i] + $koreksiStd[0][$i];
$Fval[$i] = $Fval[$i] + $koreksiStd[0][$i];
}
for($j = 0; $j < count($koreksiStd[1]); $j++ )
{
$Cval[$j] = $Cval[$j] + $koreksiStd[1][$j];
$Eval[$j] = $Eval[$j] + $koreksiStd[1][$j];
$Gval[$j] = $Gval[$j] + $koreksiStd[1][$j];
}
$valVi = 2;
$valVi2 = 50;
$valVi3 = 50;
$dividerD = 2 / sqrt(3);
$dividerA = 2 / sqrt(6);
$valURes = $resolution / $dividerA;
$stdSertifikat = [];
$UstdSertifikat = [];
$hysterisis = [];
for($i = 0; $i < count($koreksiStd[2]); $i++)
{
$stdSertifikat[$i] = $koreksiStd[2][$i];
array_push($UstdSertifikat, $stdSertifikat[$i] / 2);
}
for($i = 0; $i < count($Aval); $i++)
{
array_push($hysterisis, abs((($Cval[$i] - $Bval[$i])) +
($Eval[$i] - $Dval[$i]) +
($Gval[$i] - $Fval[$i])) / 3
);
}
$upAvg = [];
$dnAvg = [];
$upKoreksi = [];
$dnKoreksi = [];
$upStdev = [];
$dnStdev = [];
$upURepeat = [];
$dnURepeat = [];
$zeroErr = [];
$zeroErrU = [];
for($i = 0; $i < count($koreksiStd[0]); $i++)
{
$array = array(
$Bval[$i], $Dval[$i], $Fval[$i]
);
array_push($upAvg, $round->Roundto($Avg->Average($array), 1));
}
for($i = 0; $i < count($koreksiStd[0]); $i++)
{
$array = array(
$Cval[$i], $Eval[$i], $Gval[$i]
);
array_push($dnAvg, $round->Roundto($Avg->Average($array), 1));
}
for($i = 0; $i < count($Aval); $i++)
{
array_push($upKoreksi, $round->Roundto(($upAvg[$i] - $Aval[$i]), 1));
}
for($i = 0; $i < count($Aval); $i++)
{
array_push($dnKoreksi, $round->Roundto(($dnAvg[$i] - $Aval[$i]), 1));
}
for($i = 0; $i < count($Aval); $i++)
{
$array = array(
$Bval[$i], $Dval[$i], $Fval[$i]
);
array_push($upStdev, $stdev->Stdev($array));
}
for($i = 0; $i < count($Aval); $i++)
{
$array = array(
$Cval[$i], $Eval[$i], $Gval[$i]
);
array_push($dnStdev, $stdev->Stdev($array));
}
for($i = 0; $i < count($Aval); $i++)
{
array_push($upURepeat, $upStdev[$i] / (2 * sqrt(3)));
}
for($i = 0; $i < count($Aval); $i++)
{
array_push($dnURepeat, $dnStdev[$i] / (2 * sqrt(3)));
}
for($i = 0; $i < count($Aval); $i++)
{
array_push($zeroErr, max(abs($Cval[$i] - $Bval[$i]),
abs($Eval[$i] - $Dval[$i]),
abs($Gval[$i] - $Fval[$i])
));
}
//this one has the same value as u hysterisis column
for($i = 0; $i < count($Aval); $i++)
{
array_push($zeroErrU, $zeroErr[$i] / (2 * (pow(3, 0.5))));
}
$KANval = 7.5;
$UPbudgetua = [];
$UPbudgetRes = [];
$UPjumlahuicipow = [];
$UPjumlahuicivi = [];
$UPketidakpastianGab = [];
$UPkebebasanEff = [];
$UPfaktorCakup = [];
$UPketidakpastianBen = [];
$UPfinalRes = [];
for($i = 0; $i < 7; $i++)
{
array_push($UPbudgetua, $upStdev[$i], $zeroErr[$i], $resolution, 0, $stdSertifikat[$i], $hysterisis[$i], ((0.1 * $driftres[0][$i]) / 2));
$UPbudgetRes[$i] = $budget->Budget($UPbudgetua);
$UPjumlahuicipow[$i] = $round->Roundto(array_sum($UPbudgetRes[$i][6]), 3);
$UPjumlahuicivi[$i] = $round->Roundto(array_sum($UPbudgetRes[$i][7]), 3);
$UPketidakpastianGab[$i] = $round->Roundto(sqrt($UPjumlahuicipow[$i]), 3);
$UPkebebasanEff[$i] = $round->Roundto((pow($UPketidakpastianGab[$i], 4) / $UPjumlahuicivi[$i]), 3);
$UPfaktorCakup[$i] = $round->Roundto($TINV->TINV(0.05, $UPkebebasanEff[$i]), 3);
$UPketidakpastianBen[$i] = $round->Roundto($UPketidakpastianGab[$i] * $UPfaktorCakup[$i], 3);
if($UPketidakpastianBen[$i] <= $KANval)
{
$UPfinalRes[$i] = $KANval;
}
else
{
$UPfinalRes[$i] = $round->Roundto($UPketidakpastianBen[$i], 1);
}
array_splice($UPbudgetua, 0, count($UPbudgetua));
}
$DNbudgetua = [];
$DNbudgetRes = [];
$DNjumlahuicipow = [];
$DNjumlahuicivi = [];
$DNketidakpastianGab = [];
$DNkebebasanEff = [];
$DNfaktorCakup = [];
$DNketidakpastianBen = [];
$DNfinalRes = [];
for($i = 0; $i < 7; $i++)
{
array_push($DNbudgetua, $dnStdev[$i], $zeroErr[$i], $resolution, 0, $stdSertifikat[$i], $hysterisis[$i], ((0.1 * $driftres[0][$i]) / 2));
$DNbudgetRes[$i] = $budget->Budget($DNbudgetua);
$DNjumlahuicipow[$i] = $round->Roundto(array_sum($DNbudgetRes[$i][6]), 3);
$DNjumlahuicivi[$i] = $round->Roundto(array_sum($DNbudgetRes[$i][7]), 3);
$DNketidakpastianGab[$i] = $round->Roundto( sqrt($DNjumlahuicipow[$i]), 3);
$DNkebebasanEff[$i] = $round->Roundto((pow($DNketidakpastianGab[$i], 4) / $DNjumlahuicivi[$i]), 3);
// $DNfaktorCakDN[$i] = $round->Roundto($round->TINV(0.05, $DNkebebasanEff[$i]), 3);
$DNfaktorCakup[$i] = $round->Roundto($TINV->TINV(0.05, $DNkebebasanEff[$i]), 3);
$DNketidakpastianBen[$i] = $round->Roundto($DNketidakpastianGab[$i] * $DNfaktorCakup[$i], 3);
if($DNketidakpastianBen[$i] <= $KANval)
{
$DNfinalRes[$i] = $KANval;
}
else
{
$DNfinalRes[$i] = $round->Roundto($DNketidakpastianBen[$i], 1);
}
array_splice($DNbudgetua, 0, count($DNbudgetua));
}
$result = array(
$Aval,
$upAvg,
$dnAvg,
$upKoreksi,
$dnKoreksi,
$UPfinalRes,
$DNfinalRes,
$length,
);
return $result;
}
}
You need add parameters in constructor:
$index = request("tablesupmpindex");
$loop = request("loopVal");
$length = request("supmpLength");
$SUPMP = new SUPMPFunc($index, $loop, $length); <--edit

PHP sorty array by column and slice it

I am trying to sort an array based on a column value:
Example:
$cats[0]['holders'] = 55;
$cats[1]['holders'] = 66;
$cats[2]['holders'] = 77;
$cats[3]['holders'] = 23;
$cats[4]['holders'] = 64;
$cats[5]['holders'] = 82;
$cats[6]['holders'] = -3;
$cats[7]['holders'] = -5;
$cats[8]['holders'] = -17;
$cats[9]['holders'] = -25;
$cats[10]['holders'] = 66;
$cats[11]['holders'] = -10;
$cats[12]['holders'] = 0;
$cats[13]['holders'] = 5;
$cats[14]['holders'] = 4;
$cats[15]['holders'] = -3;
function compareHolders($a, $b) {
$aPoints = $a['holders'];
$bPoints = $b['holders'];
return strcmp($aPoints, $bPoints);
}
$cats = usort($cats, 'compareHolders');
I would like to get the top 5 values and bottom 5 values:
$first_5_tokens = array_slice($tokens, 0, 5, true);
print_r($first_5_tokens);
$last_5_tokens = array_slice($tokens, -5);
print_r($last_5_tokens);
This is not sorting the array for me by "holder" value. How can I do this? Thanks!
Your comparison function sorts array in descending order and also, don't use it like - $cats = usort($cats, 'compareHolders'); Instead just use it like - usort($cats, 'compareHolders');
I changed your function and did it like this.
$cats[0]['holders'] = 55;
$cats[1]['holders'] = 66;
$cats[2]['holders'] = 77;
$cats[3]['holders'] = 23;
$cats[4]['holders'] = 64;
$cats[5]['holders'] = 82;
$cats[6]['holders'] = -3;
$cats[7]['holders'] = -5;
$cats[8]['holders'] = -17;
$cats[9]['holders'] = -25;
$cats[10]['holders'] = 66;
$cats[11]['holders'] = -10;
$cats[12]['holders'] = 0;
$cats[13]['holders'] = 5;
$cats[14]['holders'] = 4;
$cats[15]['holders'] = -3;
foreach($cats as $cat) {
echo $cat['holders'] . "<br>";
}
// function compareHolders($a, $b) {
//
// $aPoints = $a['holders'];
// $bPoints = $b['holders'];
//
// return strcmp($aPoints, $bPoints);
//
// }
function compareHolders($a, $b) {
$a = $a['holders'];
$b = $b['holders'];
if ($a == $b)
return 0;
return ($a > $b) ? -1 : 1;
}
usort($cats, 'compareHolders');
echo "<h4>After</h4>\n";
foreach($cats as $cat) {
echo $cat['holders'] . "<br>";
}
// print_r($cats);
$tokens = $cats;
echo "<h4>First Five</h4>\n";
$first_5_tokens = array_slice($tokens, 0, 5, true);
print_r($first_5_tokens);
echo "<h4>Last Five</h4>\n";
$last_5_tokens = array_slice($tokens, -5);
print_r($last_5_tokens);

How to sort associative array by column that contains previous id value?

I have such associative array. The key prev contains a value to match the id value of the previous item.
When prev is 0 then it's the first item.
Correct order should be by index prev:
$data[3]
$data[1]
$data[0]
$data[4]
$data[2]
but I don't know how to achieve this.
$data[0]['id'] = 10;
$data[0]['name'] = 'Zoe';
$data[0]['prev'] = 20;
$data[1]['id'] = 20;
$data[1]['name'] = 'Tom';
$data[1]['prev'] = 40;
$data[2]['id'] = 30;
$data[2]['name'] = 'Andy';
$data[2]['prev'] = 50;
$data[3]['id'] = 40;
$data[3]['name'] = 'Kathy';
$data[3]['prev'] = 0;
$data[4]['id'] = 50;
$data[4]['name'] = 'Barbara';
$data[4]['prev'] = 10;
I think this is what you want to do:
<?php
$data = array();
$data[0]['id'] = 10;
$data[0]['name'] = 'Zoe';
$data[0]['prev'] = 20;
$data[1]['id'] = 20;
$data[1]['name'] = 'Tom';
$data[1]['prev'] = 40;
$data[2]['id'] = 30;
$data[2]['name'] = 'Andy';
$data[2]['prev'] = 50;
$data[3]['id'] = 40;
$data[3]['name'] = 'Kathy';
$data[3]['prev'] = 0;
$data[4]['id'] = 50;
$data[4]['name'] = 'Barbara';
$data[4]['prev'] = 10;
$nextId = 0;
$results = array();
while (count($data) > 0) {
$matchFound = false;
foreach ($data as $key=>$val) {
if ($val['prev'] === $nextId) {
$results[] = $val;
$nextId = $val['id'];
unset($data[$key]);
$matchFound = true;
break;
}
}
if (!$matchFound) break;
}
The outer while loops checks if the $data array still has elements. The inner for loop searches for the array with element 'prev' equal to the $nextId that we are looking for (initially set to 0). When it finds it, it assigns the id to $next, removes the element from the original array, and adds the element to our sorted array.
Do you mean order by "pre"? You want PHP's usort() function:
<?php
$data = array();
$data[0]['id'] = 10;
$data[0]['name'] = 'Zoe';
$data[0]['prev'] = 20;
$data[1]['id'] = 20;
$data[1]['name'] = 'Tom';
$data[1]['prev'] = 40;
$data[2]['id'] = 30;
$data[2]['name'] = 'Andy';
$data[2]['prev'] = 50;
$data[3]['id'] = 40;
$data[3]['name'] = 'Kathy';
$data[3]['prev'] = 0;
$data[4]['id'] = 50;
$data[4]['name'] = 'Barbara';
$data[4]['prev'] = 10;
function my_order($a,$b) {
return $a['prev'] > $b['prev'];
}
usort($data, "my_order");
print_r($data); //Kathy, Barbara, Zoe, Tom, Andy
Using the function "my_order", which compares $data[$x]['prev'] to $data[$x+1]['prev'], you can yield the results sorted by the "prev" values of the array.
You can use PHP's usort function to do so. It takes an array as the first parameter and then a comparison function as the second. From the documentation:
function cmp($a, $b){
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
$a = array(3, 2, 5, 6, 1);
usort($a, "cmp");
The comparison function returns 0 if they're equivalent, -1 if a comes before b, and 1 if b comes before a. You can order it however you like.
For you, it could look like:
function cmp($a, $b){
if ($a['prev'] == $b['prev']) {
return 0;
}
return ($a['prev'] < $b['prev']) ? -1 : 1;
}
usort($data, "cmp");
you should try this hope it helps you
$data = array();
$data[0]['id'] = 10;
$data[0]['name'] = 'Zoe';
$data[0]['prev'] = 20;
$data[1]['id'] = 20;
$data[1]['name'] = 'Tom';
$data[1]['prev'] = 40;
$data[2]['id'] = 30;
$data[2]['name'] = 'Andy';
$data[2]['prev'] = 50;
$data[3]['id'] = 40;
$data[3]['name'] = 'Kathy';
$data[3]['prev'] = 0;
$data[4]['id'] = 50;
$data[4]['name'] = 'Barbara';
$data[4]['prev'] = 10;
function sortIt($data) {
$output = array();
$key = array_search(0, array_column($data, 'prev'));
$output[] = $data[$key];
unset($data[$key]);
$data = array_combine(
array_column($data,'prev'),
$data
);
while($data){
$last = end($output);
$output[] = $data[$last['id']];
unset($data[$last['id']]);
}
return $output;
}
echo '<pre>';
print_r(sortIt($data));
You could get a bit better response time using a hash:
foreach($data as $rec) {
$hash[$rec["prev"]] = $rec;
}
$id = "0";
while (isset($hash[$id])) {
$result[] = $curr = $hash[$id];
$id = $curr["id"];
}
See it run on eval.in

How to format an associative array with another structure?

I have a query like this:
select truck, oil_type, km_min, km_max from trucks;
I'm using codeigniter and with the $query->result_array() function so its loaded in an associative array with this structure:
/*
array(
truck
oil_type
km_min
km_max
)
*/
$arr[0]["truck"] = 2;
$arr[0]["oil_type"] = 2;
$arr[0]["km_min"] = 345;
$arr[0]["km_max"] = 567;
$arr[1]["truck"] = 2;
$arr[1]["oil_type"] = 4;
$arr[1]["km_min"] = 234;
$arr[1]["km_max"] = 867;
$arr[2]["truck"] = 1;
$arr[2]["oil_type"] = 2;
$arr[2]["km_min"] = 545;
$arr[2]["km_max"] = 867;
$arr[3]["truck"] = 4;
$arr[3]["oil_type"] = 3;
$arr[3]["km_min"] = 45;
$arr[3]["km_max"] = 567;
Then, I'm trying to restructure it grouping the trucks by the id, something like this:
/*
trucks - array(
truck
truck_data - array(
oil_type
km_min
km_max
)
)
*/
$arr["truck"][0]= 2;
$arr["truck"][0]["truck_data"][0]["oil_type"] = 2;
$arr["truck"][0]["truck_data"][0]["km_min"] = 345;
$arr["truck"][0]["truck_data"][0]["km_max"] = 567;
$arr["truck"][0]["truck_data"][1]["oil_type"] = 4;
$arr["truck"][0]["truck_data"][1]["km_min"] = 234;
$arr["truck"][0]["truck_data"][1]["km_max"] = 867;
$arr["truck"][1]= 1;
$arr["truck"][1]["truck_data"][0]["oil_type"] = 2;
$arr["truck"][1]["truck_data"][0]["km_min"] = 545;
$arr["truck"][1]["truck_data"][0]["km_max"] = 867;
$arr["truck"][2]= 4;
$arr["truck"][2]["truck_data"][0]["oil_type"] = 3;
$arr["truck"][2]["truck_data"][0]["km_min"] = 45;
$arr["truck"][2]["truck_data"][0]["km_max"] = 567;
I thought in something like the code below:
$res = $query->result_array();
$cnt_total = count($res);
$y = 0;
for ($x=0; $x < $cnt_total -1 ; $x++) {
$truck = $res[$x]["truck"];
$trucks["truck"][$y] = $truck;
$q = $x + 1;
$i = 0;
do{
$trucks[$y][$i]["oil_type"] = $res[$q]["oil_type"];
$trucks[$y][$i]["km_min"] = $res[$q]["km_max"];
$trucks[$y][$i]["km_max"] = $res[$q]["km_max"];
$q++;
$i++;
if ($q <= $cnt_total) break;
} while ( $truck === $res["truck"][$q] );
$y++;
}
But does not work properly... I'm too far of the solution? The performance It's important for me in this particular case.
There is a phpfiddle where you can try:
http://phpfiddle.org/main/code/67j-ui5
Any idea, tip, or advice will be appreciated, and if you need more info, let me know and I'll edit the post.
Try this:
$res = $query->result_array();
$trucks = array();
foreach ($res as $row) {
$truck["truck"] = $row["truck"];
$truck["truck_data"] = array(
'oil_type' => $row["oil_type"],
'km_min' => $row["km_min"],
'km_max' => $row["km_max"],
);
$trucks[] = $truck;
}
var_dump($trucks);
What you've provided as a desired result is a little ambiguous. This might give what you're asking for.
$trucks=array();
$res = $query->result_array(); // assuming this is actually several trucks
foreach ($res as $r){
// set up the array from the data without writing out every column manually
$truck=array(
'truck'=>$r['truck'],
'truck_data'=>$r,
);
// remove the bit you wanted separately as 'truck' from 'truck_data'
unset($truck['truck_data']['truck']);
// push into $trucks
$trucks[]=$truck;
}
Is this what you need? conversion result is stored in $result
$result = array();
foreach($query->result_array() as $truck)
{
$new_truck = array();
$new_truck['truck'] = $truck['truck'];
$new_truck['truck_data'] = array();
$new_truck['truck_data']['oil_type'] = $truck['oil_type'];
$new_truck['truck_data']['km_min'] = $truck['km_min'];
$new_truck['truck_data']['km_max'] = $truck['km_max'];
array_push($result, $new_truck);
}

Using key function without overwritting the same keys in PHP

I'd like to extract the data from an array within an array. But the problem is, when I use the key function it overwrites the first entry. I'm expecting to have a result of 135 rows, but it only gives me back 114.
Below is the code where I'm getting a problem..
while($row1 = mssql_fetch_array($result1)) {
$mycount = $mycount + 1;
$boskey = $row1["EAN11"]."^".$row1["AUART"];
$boskey1 = $row1["ORDNUM"]."^".$row1["ERDAT"]."^".$row1["KUNAG"]."^".$row1["NAME1"]."^".$row1["PERNR"]."^".$row1["FKIMG"]."^".$row1["BASEPRICE"]."^".$row1["NETPRICE"]."^".$row1["ZZMAXDISC"]."^".$row1["MVGR1"]."^".$row1["KDGRP"];
$bos[$boskey][$boskey1] = $bos[$boskey][$boskey1];
}
for ($i = 0; $i < count($bos); $i++) {
$abc = key($bos);
$arr = explode("^",$abc);
$ean11 = $arr[0];
$auart = $arr[1];
echo $ean11 . " - " . $auart;
for ($j = 0; $j < count($bos[$abc]); $j++) { //total count of $bos[$abc] is 114.
$xxx = key($bos[$abc]);
$arr1 = explode("^",$xxx);
$ordnum = $arr1[0];
$docdate = $arr1[1];
$customer = $arr1[2];
$name1 = $arr1[3];
$ae = $arr1[4];
$qty = $arr1[5];
$baseprice = $arr1[6];
$netprice = $arr1[7];
//$discount = $arr1[8];
$booktype = $arr1[9];
$kdgrp = $arr1[10];
$discount = 100 - (100 * ( $netprice / $baseprice));

Categories