我有一个现有的数组(如下所示)......
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) ""
}
答案 1 :(得分:0)
$result = array();
foreach($yourArray as $row) {
list($key, $value) = explode(":", $row);
$result[$key] = $value;
}