2013-12-18 75 views
0

我有一個現有的陣列(如下圖所示)...如何添加關鍵現有陣列(PHP)

array(15) { 
    [0]=> 
    string(17) "orderid:100000154" 
    [1]=> 
    string(61) "shipping_method:channelunitycustomrate_channelunitycustomrate" 
    [2]=> 
    string(18) "qty_ordered:1.0000" 
    [3]=> 
    string(26) "shipping_firstname:John" 
    [4]=> 
    string(24) "shipping_lastname:Doe" 
    [5]=> 
    string(17) "shipping_company:" 
    [6]=> 
    string(36) "shipping_street1:123 Fake Street" 
    [7]=> 
    string(17) "shipping_street2:" 
    [8]=> 
    string(20) "shipping_city:LAUREL" 
    [9]=> 
    string(28) "shipping_postcode:20723-1042" 
    [10]=> 
    string(24) "shipping_region:Maryland" 
    [11]=> 
    string(19) "shipping_country:US" 
    [12]=> 
    string(21) "vendor_sku:3397001814" 
    [13]=> 
    string(16) "vendor_linecode:" 
    [14]=> 
    string(1) " 
" 
} 

我有這個數組中所期望的按鍵設置 - 第一個關鍵價值將是orderid,所以我想orderid => 1000000154

我會怎麼做呢?我相信我必須再次爆炸這個陣列,但我不確定寫這個陣列的方式,我的任何嘗試都沒有讓我更接近。

謝謝!

+0

環陣列之上,爆炸上':'和分配的鍵/值對的新數組。 –

回答

2

只需循環並使用explode()設置鍵和值。使用展開陣列中的第一個項目作爲鍵,第二個項目作爲值,然後取消設置現有項目(數字索引的數組元素)進行清理。

$input = array(
    "orderid:100000154", 
    "shipping_method:channelunitycustomrate_channelunitycustomrate", 
    "qty_ordered:1.0000", 
    "shipping_firstname:John", 
    "shipping_lastname:Doe", 
    "shipping_company:", 
    "shipping_street1:123 Fake Street", 
    "shipping_street2:", 
    "shipping_city:LAUREL", 
    "shipping_postcode:20723-1042", 
    "shipping_region:Maryland", 
    "shipping_country:US", 
    "vendor_sku:3397001814", 
    "vendor_linecode:", 
    " 
    " 
); 

foreach($input as $key => $val) { 
    if(strstr($val, ":")) { 
     $exploded = explode(":", $val); 
     $input[$exploded[0]] = $exploded[1]; 
    } 
    unset($input[$key]); 
} 
echo "<pre>"; 
var_dump($input); 
echo "</pre>"; 

輸出:

array(14) { 
    ["orderid"]=> 
     string(9) "100000154" 
    ["shipping_method"]=> 
     string(45) "channelunitycustomrate_channelunitycustomrate" 
    ["qty_ordered"]=> 
     string(6) "1.0000" 
    ["shipping_firstname"]=> 
     string(4) "John" 
    ["shipping_lastname"]=> 
     string(3) "Doe" 
    ["shipping_company"]=> 
     string(0) "" 
    ["shipping_street1"]=> 
     string(15) "123 Fake Street" 
    ["shipping_street2"]=> 
     string(0) "" 
    ["shipping_city"]=> 
     string(6) "LAUREL" 
    ["shipping_postcode"]=> 
     string(10) "20723-1042" 
    ["shipping_region"]=> 
     string(8) "Maryland" 
    ["shipping_country"]=> 
     string(2) "US" 
    ["vendor_sku"]=> 
     string(10) "3397001814" 
    ["vendor_linecode"]=> 
     string(0) "" 
} 
0
$result = array(); 
foreach($yourArray as $row) { 
    list($key, $value) = explode(":", $row); 
    $result[$key] = $value; 
}