I have an existing array (as seen below)...
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) "
"
}
I have a desired key setup in this array -- the key for the first value would be orderid, so I'd like orderid => 1000000154
How would I go about this? I believe I have to explode the array again, but I'm not sure about the way to write it and none of my attempts have gotten me any closer.
Thanks!
Just loop through and set the keys and values using explode()
. Use the first item in the exploded array as the key and the second as the value, then unset the existing item (the numeric-indexed array element) to clean up.
$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>";
Outputs:
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;
}