MR.Internet
MR.Internet

Reputation: 645

Split array value and use it as key

I have the following array:

Array
(
    [0] => 102 [30:27]
    [1] => 110 [29:28]
    [2] => 103 [30:27]
)

The output I need is as follows:

Array
(
    [102] => 30:27
    [110] => 29:28
    [103] => 30:27
)

How can I do this?

Upvotes: 0

Views: 79

Answers (3)

Nambi
Nambi

Reputation: 12042

try

$new_arr=array();


foreach($b as $k=>$v)
{
    $v=explode(' ',$v);
    //var_dump($v);
    $v[1]=str_replace(array('[',']'),array('',''),$v[1]);
    $new_arr[$v[0]]=$v[1];
}

print_r($new_arr);

output:

Array ( [102] => 30:27 [110] => 29:28 [103] => 30:27 )

Upvotes: 0

Amal Murali
Amal Murali

Reputation: 76646

You can loop through the array, use a regular expression to capture both the number and value, and then build a new array with the number as the index:

$result = array();

foreach ($array as $key => $value) {
    if (preg_match('~(\d+)\s+\[(.*)]~', $value, $matches)) {
        $index = isset($matches[1]) ? $matches[1] : $key;
        $value = isset($matches[2]) ? $matches[2] : $key;
        $result[$index] = $value;
    }
}

print_r($result);

Demo.


If the array values are always delimited by a single space, then a regular expression isn't necessary. You could use explode() to split the array value with space as a delimiter and then get the index and value to build the new array:

$result = array();

foreach ($array as $key => & $value) {
    $parts = explode(' ', $value);
    $index = $parts[0];
    $result[$index] = substr($parts[1], 1, -1);
}

print_r($result);

Output:

Array
(
    [102] => 30:27
    [110] => 29:28
    [103] => 30:27
)

Demo.

Upvotes: 1

SamV
SamV

Reputation: 7586

If the data is consistent then is there any need for expensive regex? Here's the working version.

$array = array(
    '102 [30:27]',
    '110 [29:28]',
    '103 [30:27]'
);

$new = array();

array_walk($array, function($element) use (&$new) {
    $parts = explode(" ", $element);
    $new[$parts[0]] = trim($parts[1], ' []');
});

var_dump($new);

Upvotes: 1

Related Questions