Reputation: 609
I want to manipulate an array and i'm a bit stuck on how to proceed and hoping i can be pointed to the right direction
This is the array i currently have:
array(10) {
["gdlr-room-id"]=> string(4) "3595"
["gdlr-check-in"]=> string(10) "2016-10-31"
["gdlr-night"]=> string(1) "1"
["gdlr-check-out"]=> string(10) "2016-11-01"
["gdlr-room-number"]=> string(1) "1"
["gdlr-adult-number"]=> string(1) "1"
["gdlr-children-number"]=> string(1) "1"
["gdlr-resident"]=> string(8) "resident"
["service"]=> string(19) "5061,5060"
["service-amount"]=> string(7) "1,1" }
And this is what i want to achieve:
array(10) {
["gdlr-room-id"]=> array(1) { [0]=> string(4) "3595" }
["gdlr-check-in"]=> string(10) "2016-10-31"
["gdlr-night"]=> string(1) "1"
["gdlr-check-out"]=> string(10) "2016-11-01"
["gdlr-room-number"]=> string(1) "1"
["gdlr-adult-number"]=> array(1) { [0]=> string(1) "1" }
["gdlr-children-number"]=> array(1) { [0]=> string(1) "1" }
["gdlr-resident"]=> string(8) "resident"
["service"]=> array(2) { [0]=> string(4) "5061" [1]=> string(4) "5060" }
["service-amount"]=> array(2) { [0]=> string(1) "1" [1]=> string(1) "1" }
}
If i can explain a bit more: if we take the key gdlr-room-id as an example: my current array represents a key, value pair as shown ["gdlr-room-id"]=> string(4) "3595"
while my desired result is for the value to be inside another array as shown: ["gdlr-room-id"]=> array(1) { [0]=> string(4) "3595" }
. This is not for all the key=>value pairs but only a select few as some would remain as they are e.g. ["gdlr-check-in"]=> string(10) "2016-10-31"
is ok as it is
In summary, how do i take some values inside an array(as my current one is) and make some values be inside another array as i have explained above? and while we're at it, any suggestion how i can turn this ["service"]=> string(19) "5061,5060"
into this: ["service"]=> array(2) { [0]=> string(4) "5061" [1]=> string(4) "5060" }
? thanks
Upvotes: 0
Views: 94
Reputation: 9022
If you have a list of keys for which the value should be expanded into arrays, e.g.
$expand_keys = array('gdlr-room-id', 'service');
and multiple values are separated by commas, you could do something like
foreach ($array as $key => $value) {
if (in_array($key, $expand_keys)) {
$array[$key] = explode(',', $value);
}
}
This will check each key-value pair of your original array and explode its value into an array if the key is in the $expand_keys array.
Upvotes: 3
Reputation: 1528
You can loop through the elements and explode the values into a new array like this:
<?php
$array = array("gdlr-room-id" => "3595",
"service" => "5061,5060",
"service-amount" => "1,1"
);
$copied_array = array();
foreach( $array as $key => $value ){
$copied_array[$key] = explode(',', $value);
}
print_r($copied_array);
Upvotes: 2