2011-12-17 14 views
1
$shop = array(array(Title => "rose", 
        Price => 1.25, 
        Number => 15 
       ), 
      array(Title => "daisy", 
        Price => 0.75, 
        Number => 25, 
       ), 

      array(Title => "orchid", 
        Price => 1.15, 
        Number => 7 
       ) 
     ); 

私はこのような配列を持っています。この配列を以下のようにKEYWORDに変換したい。どうやってやるの?キー配列で多次元配列を変換する

$shop = array ("rose" => Price => 1.25, 
         Number => 15),          
      "daisy" => Price => 0.75, 
         Number => 25),         
      "orchid" => Title => "orchid", 
         Price => 1.15) 
      ); 

答えて

4
$shopsOriginal = array(array(Title => "rose", 
        Price => 1.25, 
        Number => 15), 
       array(Title => "daisy", 
        Price => 0.75, 
        Number => 25), 
       array(Title => "orchid", 
        Price => 1.15, 
        Number => 7)); 

$shops = array(); 

foreach ($shopsOriginal as $shop) { 
    $title = $shop['Title']; // Store the title for this shop 
    unset($shop['Title']); // Remove the title of the shop from the shop information array 
    $shops[$title] = $shop; // Set the shop information in the shops array using the shop's title as key 
} 

var_dump($shops); 
+1

返信ありがとうございました... –

0
$shop = array(array('Title' => "rose", 
'Price' => 1.25, 
'Number' => 15 
), 
array('Title' => "daisy", 
'Price' => 0.75, 
'Number' => 25, 
), 

array('Title' => "orchid", 
'Price' => 1.15, 
'Number' => 7 
) 
); 


$new_array = ARRAY(); 

foreach ($shop AS $sub_arr) { 
    //$new_array[$sub_arr['Title']]['Price'] = $sub_arr['Price']; 
    //$new_array[$sub_arr['Title']]['Number'] = $sub_arr['Number']; 

    // edit: adapted to Michael Robinson 
    $this_title = $sub_arr['Title']; 
    unset($sub_arr['Title']); 
    $new_array[$this_title] = $sub_arr; 
} 

var_dump($new_array); 
?> 
+0

ありがとうございました**私のために**働いています** –

+1

誰かがあなたよりも良い答えを提供している場合は、自分のものを編集して自分のものを編集するのではなく、彼らの! – liquorvicar

+0

@liquorvicar:right、up-voted。 – djot

0

これを試してみてください。

$items = array(); 
foreach ($shop as $item) { 
$index = $item['Title']; 
unset($item['Title']); 
$items[$index] = $item; 
} 
print_r($items); 

プリントアウト:

Array 
(
[rose] => Array 
    (
     [Price] => 1.25 
     [Number] => 15 
    ) 

[daisy] => Array 
    (
     [Price] => 0.75 
     [Number] => 25 
    ) 

[orchid] => Array 
    (
     [Price] => 1.15 
     [Number] => 7 
    ) 

) 

このことができます願っています。