Create a new table based on another – PHP – SitePoint Forums

I have

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


and I try to create another array from it

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

5 and 7 means these slots are covered, the slot key is the start slot and the pole key is the breaker size (its value can be 1, 2 or 3) (as seen by)

Is this a good start?

$slots  = array();

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

Well, if the net result is that the $slots array ends up being an array of numbers of course. Suppose you have two locations in $circuit_breakerArray. One 2-pole and one 3-pole. 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 the end list isn’t exactly what you had in mind. But if you read your code and see the response, you can see why this would happen. Maybe you want to create an array of arrays? As [5 => [7], 6 => [8, 10]]?

What is the use of your end result? Just to know which slots contain something?

$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 several ways to do it, one of which is to check the size of the array before and after uniqueness)

I have a select box, which contains all available slots in this panel


But I would like to remove the slots used by the circuit breakers in the panel.
something like using a foreach() to eliminate used slots


Close. You want the difference of the arrays, not their merging.

$used_slots = [];
foreach($circuit_breakerArray as $slot) {
  $used_slots = array_merge($used_slots,range($slot['slot'],$slot['slot']+$slot['poles']));
$available_slots = array_diff(range(1,$row['slots']),array_unique($used_slots));

(EDIT: if you don’t want $used_slots after that, you can change it to do the diff inside the loop instead)

1 like

James S. Joseph