问题描述:

I have an array that looks like this:

a 12 34

b 12345

c 123456

So the array looks like

$array[0] = "a 12 34"

$array[1] = "b 12345"

$array[2] = "c 123456"

I am trying to create an associative array such that

[a] => 12 34

[b] => 12345

[c] => 123456

Can I possibly split the array into two, one for containing "a, b, c" and another for their contents and use the array_combine()? Or are there any other ways?

网友答案:

You can do that within a loop like the snippet below demonstrates. Quick-Test here:

        $array      = array("a 12 34", "b 12345", "c 123456");
        $array2     = array();

        foreach($array  as $data){
            preg_match("#([a-z])(\s)(.*)#i", $data, $matches);
            list(, $key, $space, $value)    = $matches;
            $array2[$key]   = $value;
        }

        var_dump($array2);
        // YIELDS::
        array(3) {
            ["a"]=>  string(5) "12 34"
            ["b"]=>  string(5) "12345"
            ["c"]=>  string(6) "123456"
        }

Or using a Blend of array_walk() and array_combine() which can be Quick-Tested Here.

        <?php

            $array      = array("a 12 34", "b 12345", "c 123456");
            $keys       = array();

            array_walk($array, function(&$data, $key) use (&$keys){
                $keys[] = trim(preg_replace('#(\s.*)#i',   '', $data));;
                $data   = trim(preg_replace('#(^[a-z])#i', '', $data));
            });

            $array = array_combine($keys, $array);

            var_dump($array);;
            // YIELDS::
            array(3) {
                ["a"]=>  string(5) "12 34"
                ["b"]=>  string(5) "12345"
                ["c"]=>  string(6) "123456"
            }
网友答案:

You can do it without any difficulty :) A simple loop is possible to do it.

  1. Create new array
  2. Lopp on each row
  3. Split each data (explode(' ', $row, 2), strstr, substr, ...) ?
  4. Put data on your new array $array[$key] = $value;
网友答案:

$newArr will give your expected results

$array = array();
$array[0] = "a 12 34";
$array[1] = "b 12345";
$array[2] = "c 123456";

$newArr = array();

foreach($array as $val) {
    $values = explode(' ', $val, 2);
    $newArr[$values[0]] = $values[1];
}

print_r($newArr, true);
网友答案:

You could use a combination of array_map, array_column and array_combine:

$array = array_map(function ($v) { return explode(' ', $v, 2); }, $array);
$array = array_combine(array_column($array, 0), array_column($array, 1));
相关阅读:
Top