user3682205
user3682205

Reputation: 241

creating a multi-dimensional array where key has multiple values

I am generating a multidimensional array in the format:

Array ( 
  [0] => Array ( 
         [UAM 355T] => Array ([v1] => 1000 ) ) 
  [1] => Array ( 
         [UAM 355T] => Array ( [v2] => 2000 ) ) 
  [2] => Array ( 
         [UAP 702X] => Array ( [v3] => 3000 ) ) 
  [3] => Array ( 
          [UAP 702X] => Array ( [v4] => 4000 ) ) 
    ) 

Using the php script:

 $p = 0;
   while($p < $entries[$i])
       {
     $garage_record[] = array( $license[$i]=> array( $details[$p] =>    $cost[$p]));
    $p++;
    }


 print_r($garage_record);

Though I wanted it to be a two dimensional array where a license plate is linked to multiple entries in the form;

Array ( 
  [UAM 355T] => Array ([v1] => 1000 ), 
                      ([v2] => 2000)) 
  [UAP 702X] => Array(([v1] => 1000 ), 
                      ([v2] => 2000)) 
    ) 

Thanks

Upvotes: 1

Views: 40

Answers (2)

Bryan Zwicker
Bryan Zwicker

Reputation: 652

You're probably looking for something like this:

foreach($records as $recordkey => $recordvalue) {
  foreach($recordkey as $subrecord) {
    $result[$recordkey][] = $subrecord;
  } 
}
print_r($result);

Upvotes: 0

Rapha&#235;l Mali&#233;
Rapha&#235;l Mali&#233;

Reputation: 4012

It's basic array manipulation, you can achieve what you want to do like that:

$p = 0;
while($p < $entries[$i])
{
   if (!isset($garage_record[$license[$i]]))
      $garage_record[$license[$i]] = array();

   $garage_record[$license[$i]][$details[$p]] = $cost[$p];
   $p++;
}

print_r($garage_record);

Upvotes: 1

Related Questions