简体   繁体   中英

PHP - Help building a multi dimensional array

I would like to know how to get the values into this array. Can someone please help?

Each box whether it is the in or outbox should only be listed once and then have multiple ids associated with them. I need to be able to tell which id came from what box. The ids that are in the array are only samples.

$arr = 
array(
       'Inbox'=> array('id' => array(8, 9, 15)),
       'Outbox'=> array('id' => array(8, 9, 15))
    );

Thanks


$inbox = $db->Query("SELECT * FROM mail_inbox");
$outbox = $db->Query("SELECT * FROM mail_outbox");


foreach($inbox as $key => $array)
{
  $output['Inbox']]['id'][] = $array['msg_seq'];
}
foreach($outbox as $key => $array)
{
  $output['Outbox']]['id'][] = $array['msg_seq'];
}

print_r($output);

This will give me the db fields from the inbox but I have no idea how to get the outbox in there as well. I also get undefined index for ['Box']

Now that I know what you are saying, to input stuff, do something like this to input it into the array:

$ID = 9;
$box = "Inbox";
$arr[$box]['id'][] = $ID;

or

$IDs = array(9,5,13);
$box = "Inbox";

$array = array($box => $IDs);

or if you were getting it from a Database

$dbarray[0] = array('ID' => 9,
                 'Box' => 'Outbox');

foreach($dbarray as $key => $array)
{
    $output[$array['Box']]['ids'][] = $array['ID'];
}

Multi deminsional arrays

The key or index is the first bracket

$array[key]="foo" 

is the same as

$array = array('key' => 'foo');

if there is a second bracket, it of the array inside the value part of an array. IE

$array['key']['key2'] = "bar";

is the same as

$array = array('key' => array('key2' => 'bar'));

Basically, multideminsional arrays are just arrays inside of arrays.


foreach($arr as $box => $array)
{
   echo $box;
   // $box = The Box
    foreach($array['ids'] as $ID)
   {
      echo $ID . ",";
      // $ID = The ID 
   }
   echo "<br>";
}

Sample:

Outbox 9,13,15,
Inbox 9,13,15,

This goes through each box, echos the box name, and each ID inside of the box, and echos the ID.

To access only one box

foreach($arr['Inbox'] as $ID)
{
    echo $ID . ",";
}

Sample Output:

9,13,15,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM