Create a new array based on another – PHP – SitePoint

I have

Array
( [0] => Array ( [slot] => 5 [poles] => 2 [operational_status] => 1 [x_coord] => 0 [y_coord] => 186 ) )

and am trying to create another array from it

[slots] => Array([5][7])

5 and 7 mean that those slots are covered, the slot key is the starting slot, and the poles key is the size of the breaker(its value can be 1, 2, or 3) (as seen by)

Is this a good start?

$slots = array(); foreach($circuit_breakerArray as $slot) { switch($slot['poles']) case 1: array_push($slots,$slot['slot']); break; case 2: array_push($slots,$slot['slot'],$slot['slot'] + 2); break; case 3: array_push($slots,$slot['slot'],$slot['slot'] + 2,$slot['slot'] + 4); break;

Well if the net result is that the $slots array ends up being an array of numbers sure. Lets assume you have two slots in $circuit_breakerArray. One with 2 poles and one with 3 poles. Your code would end up having $slots containing values like… [5, 7, 6, 8, 10]

Which is for slot 5 (with 2 poles) and slot 6 (with 3 poles). Something tells me that the ending list is not exactly what you had in mind. But if you read your code and you see the answer, you can see why this would be happening. Maybe you want to create an array of arrays? like [5 => [7], 6 => [8, 10]]?

What’s the usage for your end result? Just to know which slots have something in them?

$slots = [];
foreach($circuit_breakerArray as $slot) { $slots = array_merge($slots,range($slot['slot'],$slot['slot']+$slot['poles']));
}
$slots = array_unique($slots);

(If you’re doing collision detection, there are a few ways to do it, one of which being to check the size of the array before and after unique’ing)

Leave a Reply

Your email address will not be published.