Search code examples
phparraysfunctionarray-splice

How to Split Array Value same first character into a key and last character into a value


I have tried to split an Array Value with the same first character into a key and last character into a value. Here is an example. $array :

    (
        [0] => a6
        [1] => a7
        [2] => b2
        [3] => b7
        [4] => c7
        [5] => c6
        [6] => d6
        [7] => d7
        [8] => e3
        [9] => e0
     )

I want to make a new $array like this :

 (          [a] => 67
            [b] => 27
            [c] => 76
            [d] => 67
            [e] => 30    )

So far I have tried this function code :

function array_split($array, $pieces=2) 
            {   
                if ($pieces < 2) 
                    return array($array); 
                $newCount = ceil(count($array)/$pieces); 
                $a = array_slice($array, 0, $newCount); 
                $b = array_split(array_slice($array, $newCount), $pieces-1); 
                return array_merge(array($a),$b); 
            } 

        $arrayz =  array_split($array, 5);

but this code has the following results : $arrayz :

(
    [0] => Array
        (
            [0] => a6
            [1] => a7
         )

    [1] => Array
        (
            [0] => b2
            [1] => b7
          )

    [2] => Array
        (
            [0] => c7
            [1] => c6
           )

    [3] => Array
        (
            [0] => d6
            [1] => d7
            )

    [4] => Array
        (
            [0] => e3
            [1] => e0
           )

)

What should the function be to get the result?


Solution

  • Easiest solution:

    $res = [];
    foreach ($array as $v) {
        $res[$v[0]] = isset($res[$v[0]]) ? $res[$v[0]].$v[1] : $v[1];
    }
    
    print_r($res); 
    

    Where $array is ['a6','a7','b2', 'b7','c7','c6','d6','d7','e3','e0']