skip to Main Content

I have the following array:

Array
(
    [Banana] => Array
        (
            [0] => Array
                (
                    [0] => 57
                )
            [1] => Array
                (
                    [0] => 58
                )
            [2] => Array
                (
                    [0] => 59
                )
        )
)

Does PHP have a magic function to return something like this:

Array
(
    [Banana] => 57,58,59
)

Thanks.

2

Answers


  1. I don’t recognize any magic function like this but you can easily achieve it using the following:

    function magicTrick($array) {
        return array_combine(array_keys($array), array_map(function($values) {
            return implode(',', array_map(function($value) {
                return $value[0];
            }, $values));
        }, $array));
    }
    

    How it works:

    1. Iterates through the each entry to merge the values into string using the implode function,
    2. combine the results with the initial array keys using the array_combine function.
    Login or Signup to reply.
  2. The implode function is used to join elements of an array with a delimiter in between them.

    In your case, you want to iterate over the elements of the outer array and replace their contents with a string of comma separated values, correct?

    foreach ($your_array as &$value) {
      $value = implode(',', $value);
    }
    

    Alternatively, you could use array_map.

    $your_array = array_map(fn($value) => implode(',', $value), $your_array);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search