如何将密钥添加到现有数组(PHP)

如何将密钥添加到现有数组(PHP),php,arrays,Php,Arrays,我有一个现有的数组(如下所示) 我在这个数组中有一个所需的键设置——第一个值的键是orderid,所以我希望orderid=>1000000154 我该怎么办?我相信我必须再次爆炸数组,但我不确定如何编写它,我的任何尝试都没有让我更接近 谢谢 只需循环使用explode()设置键和值即可。使用分解数组中的第一项作为键,第二项作为值,然后取消设置现有项(数值索引数组元素)以进行清理 $input = array( "orderid:100000154", "shipping_met

我有一个现有的数组(如下所示)

我在这个数组中有一个所需的键设置——第一个值的键是orderid,所以我希望orderid=>1000000154

我该怎么办?我相信我必须再次爆炸数组,但我不确定如何编写它,我的任何尝试都没有让我更接近


谢谢

只需循环使用
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>";

在数组上循环,在
上分解,并将键/值分配给新数组。
$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) ""
}
$result = array();
foreach($yourArray as $row) {
    list($key, $value) = explode(":", $row);
    $result[$key] = $value;
}