Loop through two arrays

I have 2 arrays

$racks2 = 
(
    [0] => Array
        (
            [Rack_Id] => 1
            [Device] => Power Boi
            [Device_Id] => 1
        )
...
)
$racks = (
    [0] => Array
        (
            [Title] => Racky
            [Rack_Id] => 1
        )
...
)

I am trying to figure out how to loop through the first one so that it loops through the second one as long as the key (Rack_Id) are the same, is the correct way to do this like…

foreach($racks2 as $key => $value) {
...
    foreach($racks[$key] as $value) {
...
    }
}

This post may be of interest:

1 Like

You’re saying “… as long as the key (Rack_Id) are the same …”, yet the code you posted doesn’t access Rack_Id anywhere, so how it is supposed to work?

A) Your example doesn’t contain enough information to help you. You would need to show enough example data and the result you expect from that data so that someone would know what you mean by ‘it loops through the second one as long as the key (Rack_Id) are the same’. Show at least two pieces of data in the first array and show both matching and non-matching data in the second array. The way I read the example is that you want to get the matching ‘title’, and perhaps other values, out of $racks, for the current rack_id.
B) In your proposed code, the $key value is the numerical [0] index, having nothing to do with the rack_id values. If doing this in php was the best way (see the next point in this list), indexing/pivoting the data, using the rack_id values, rather than the zero referenced numerical index, when you fetch it, would allow you to directly access any related data, rather than to loop over all data to try and find it.
C) Since this is related/relational data values, the ‘R’ in RDBMS, just do all of this in one query, then produce the output you want from the data that the query matches.

ok, I have 2 arrays.
One holds all the racks (title, rack_id)
The 2nd array hold devices which have a rack_id)
So im trying to get all the devices which would have a rack_id.
So would something like this be better?

foreach($racks['Rack_Id'] as $rack) {
//rack  detail
    foreach($devices as $device) {
    //device associated with rack
   }

}

And I couldnt see a connection on the file uploading link…

the first $key is the array-key, 0 from your example, you have to explicit call the Rack_Id by its index, $racks2[0][‘Rack_Id’] or in a loop like

foreach($racks as $rack){
 foreach($devices as $device)
  if($rack['id'] === $device['id']) ...
}

look up the examples in the documentation

https://www.php.net/manual/de/control-structures.foreach.php

1 Like

@lurtnowski,

What btext editor are you usintg? If you are unable to view variables or step through then…

With so little information and data it is difficult to know what is required but anyway this is how I would tackle the problem:

<?php declare(strict_types=1);


$racks2 = [
 0 => [
  'Rack_Id' => 0,
  'Device' => 'Zero Poser Boi',
  'Device_Id'  => 0,
],
 1 => [
  'Rack_Id' => 1,
  'Device' => 'First Poser Boi',
  'Device_Id'  => 1,
],
 2 => [
  'Rack_Id' => 2,
  'Device' => 'Second Poser Boi',
  'Device_Id'  => 2,
],
];

# $racks = [
$devices = [
  0 => [
    'Title' => 'Zero Racky',
    'Rack_Id' => 0
  ],
  1 => [
    'Title' => 'First Racky',
    'Rack_Id' => 1
  ],
  2 => [
    'Title' => 'Second Racky',
    'Rack_Id' => 2
  ],
];


// ======================================
  foreach($racks2 as $rack)
  {
    echo '<br>$rack["Device_Id"] ==> ' .$rack['Device_Id'] .'<br>';
    if(1===$rack['Device_Id']) :
      show_match($rack['Device_Id'], $devices);
    endif;  
  }
// ======================================



// ========================================
echo '<h1>DEBUG Stuff </h1>';


fred($racks2, '$racks2');
fred($devices, '$devices');

//=================================================
function show_match($dev_id, $devices)
{
  echo '<br><hr>';
  echo 'Function: ' .__function__;
  echo '<hr>';
}

//======================================================
function fred($val, $title='')
{
  echo '<pre>' .$title .'==> ' . gettype($val) .'<br>';
    print_r($val);
  echo '</pre>';  
}

Please copy and paste and try to understand exactly what is happening :slight_smile:

1 Like

Meanwhile, this is what i consider to be the problem:

… Why?

2 Likes

I only broke it up into two arrayscause I didnt know how to make the comparison, but I can make an array like

$devices =[
  0 => [
           'Rack_Id' => 0,
            'Rack_Title' => 'Racky',
            'Device' => 'Zero Poser Boi',
            'Device_Id' => 0
        ),
  1 => [
           'Rack_Id' => 1
            'Rack_Title' => 'Racky1',
            'Device' => 'Zero Poser Boi1',
            'Device_Id' => 1
        ), 
  2 => [
           'Rack_Id' => 0,
            'Rack_Title' => 'Racky',
            'Device' => 'Zero Poser Boi',
            'Device_Id' => 2
        )
};

But since I wanted to list all the devices of a certain Rack_Id along with the title of the rack.
So I thought it would be best to have 1 array to hold all the racks and another to hold the devices, then just loop though the racks and looping through the devices for every rack. Is that not the way to do it

Well instead of building the array with an open KEY, e.g.

$devices[] = $row;

You can use both DB fields and hard coded KEYs to build the array in a more defined fashion.

$devices[$row['Rack_Id']]['Rack'] = $row;
$devices[$row['Rack_Id']]['Devices'][$row['Device_Id']] = $row; 

Then when rendering to the page you can use DB fields related to the RACK in the outside loop using the ‘Rack’ KEY and Device fields in the inner loop with the ‘Devices’ KEY.

foreach($devices as $Rack_Id => $ar):
	if(!empty($Rack_Id)):
		//in this loop echo anything Rack Related under the key Rack.
		echo $devices[$Rack_Id]['Rack']['Rack_Id'].'<br>';
		echo $devices[$Rack_Id]['Rack']['Rack_Title'].'<br>';
		
		//Then loop through all devices on the rack and use the fields related to devices
		foreach($devices[$Rack_Id]['Devices'] as $Device_Id => $arr): 
			if(!empty($Device_Id)):
				echo $devices[$Rack_Id]['Devices'][$Device_Id]['Device_Id'].'<br>';
				echo $devices[$Rack_Id]['Devices'][$Device_Id]['Device'].'<br>';
			endif;
		endforeach;
	endif;
endforeach;

Anyway, something like this should work. Untested.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.