neptune
neptune

Reputation: 1261

Creating an associative array with keys from a simple indexed array of strings

I have an array of strings with a format of key: value like this:

Array
    (
         [0] => label: productlabel
         [1] => timezone: SDT
         [2] => price: 0.2225
         [3] => reserve: 60
    )

I need to create an associative array with the key part as the array element index and value part as the array element value, like this:

Array
    (
        [label] => productlabel
        [timezone] => SDT
        [price] => 0.22255
        [reserve] => 60
    )

Is there a shorter way or a function to create this, or I need to make it manually with basic control structures?

Upvotes: 1

Views: 179

Answers (4)

Don't Panic
Don't Panic

Reputation: 41820

If you convert the : to =, the strings are like .ini lines, so you could treat it like that.

$assoc = parse_ini_string(str_replace(': ', '= ', join("\n", $array)));

Upvotes: 1

Cava
Cava

Reputation: 5672

You can create a new array and split in ':' after set the $key and $value.

$oldArray = [
    'label: productlabel',
    'timezone: SDT',
    'price: 0.2225',
    'reserve: 60',
];

$newArray = [];

foreach($oldArray as $pos) {
    list($key, $value) = explode(':', $pos);
    $newArray[$key] = $value;
}

Upvotes: 1

clearshot66
clearshot66

Reputation: 2302

Split each based on the : , then add to the new array

foreach($array as $value){   // loop the original array
  $split = explode(":",$value);  // split values based on : into 2 element array
  $array2[$split[0]] = $split[1];  // add to the new array, [key] = [value]
}

Upvotes: 1

Mark Baker
Mark Baker

Reputation: 212452

Map the array splitting the value on : and then use array_column() to assign the values and keys from that split:

$originalArray = [
    'label: productlabel',
    'timezone: SDT',
    'price: 0.2225',
    'reserve: 60',
];

$newArray = array_column(
    array_map(
        function($value) {
            return explode(': ',$value);
        },
        $originalArray
    ),
    1,
    0
);

var_dump($newArray);

Upvotes: 1

Related Questions