简体   繁体   中英

Split array to create an associative array

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 ? 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;

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM