以键格式转换多维数组

时间:2011-12-17 09:12:01

标签: php

$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 
                )
         );

我有这样的数组。我想像下面那样按键转换这个数组。我怎么能这样做?

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

3 个答案:

答案 0 :(得分: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);
?>

答案 2 :(得分: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
    )

)

希望这会有所帮助。