-2

I have an array that has been sorted ($sortProgDetails):

items: array:3 [▼
    1 => array:4 [▶]
    0 => array:4 [▶]
    2 => array:4 [▶]
]

I then want to loop through it in the way it currently appears but using the key as 0,1,2, not by 1,0,2. How can i achieve this?

Example of the loop where i want to return the row id on item with key = 1, then 0, then 2. so instead of the first $key = 1, i want that to be 0.

foreach ($sortProgDetails as $key=>$progDetails) {
     $getCurrentRow = Programmes::where('reference', $sortProgDetails [$key]['reference'])->get()[0]['id'];
}

jkthompson83
  • 303
  • 2
  • 10

3 Answers3

0

If you want to loop it in the order it is but have a counter, then add it

$i=0;
foreach ($sortProgDetails as $key=>$progDetails) {
    //you can use the variable $i here wich will be 0, 1, 2...
    $getCurrentRow = Programmes::where('reference', $progDetails['reference'])->get()[0]['id'];
    $i++; 
}

If you want to loop it in the old order, then use the traditional way, with for()

for($i = 0; $i < count($sortProgDetails); $i++) {
     $getCurrentRow = Programmes::where('reference', $sortProgDetails [$i]['reference'])->get()[0]['id'];
}

N69S
  • 12,981
  • 3
  • 18
  • 33
0

You can use a for loop and set the index to retrieve using the counter:

for ($i = 0; $i < count($sortProgDetails); $i++) {
  $getCurrentRow = Programmes::where('reference', $sortProgDetails[$i]['reference'])->get()[0]['id'];`
}
ADyson
  • 51,527
  • 13
  • 48
  • 61
-2

i think this is all you need and your answer:

you need ksort :

ksort($sortProgDetails);

look at this link: click