1

I’ve got an array which looks like this:

Array
(
    [0] => Array
        (
            [0] => Thomas
            [1] => Jansen
        )

    [1] => Array
        (
            [0] => Lisa
            [1] => Meier
        )

    [2] => Array
        (
            [0] => Gerda
            [1] => Ohm
        )

)

What I would like to achieve is an array like this:

Array
(
    [0] => "Jansen, Thomas"
    [1] => "Meier, Lisa"
    [2] => "Ohm, Gerda"
)

Thanks for your help!

8
  • extract(array_walk($array, function(&$value) { $value = implode(', ', $value); } ), EXTR_PREFIX_ALL, 'string_'); Commented Aug 23, 2014 at 11:20
  • But if you have an array, then it's generally better to work with that array than to set each element as an individual variable Commented Aug 23, 2014 at 11:21
  • Thanks for the advice. I edited my question. Is it possible to make a one dimensional array from the original array like the one I added to my question? Commented Aug 23, 2014 at 11:32
  • array_walk($array, function(&$value) { $value = implode(', ', $value); } ); will convert $array from a two-dimensional array to a one-dimensional array Commented Aug 23, 2014 at 11:37
  • I get a syntax error, unexpected T_FUNCTION when adding your snippet to my php file. Do I need PHP 5.3 to run the function? Commented Aug 23, 2014 at 11:43

3 Answers 3

3

you can use array_map and implode to get your results

http://php.net/manual/de/function.array-map.php

https://www.php.net/manual/de/function.implode.php

$myData = array_map(function($v){
    return implode(', ', array_reverse($v));
}, $array); 

// $myData holds
Array
(
   [0] => "Jansen, Thomas"
   [1] => "Meier, Lisa"
   [2] => "Ohm, Gerda"
)

it is better to work with the returned array $myData = array_map(... like foreach or $myData[0] then set each element into its own variable.


Edit after comment

PHP <= 5.3 implementation

function getStrings($v)
{
    return implode(',', array_reverse($v));
}
$myData = array_map('getStrings', $array); 
Sign up to request clarification or add additional context in comments.

2 Comments

,but OP requires Jansen, Thomas and it'll print Thomas, Jansen!
@ShaunakShukla thanks for the hint i didn't notice this - i updated my answer
2
$array  = array(.... your array ....);
$array2 = array();
foreach($array as $val) {
   $array2[] = $val[1].', '.$val[0];
}

Here is an example: http://codepad.org/qsaQp9sp

You achieve the same result like in ins0's answer, so you can choose what you like more.

Comments

1
foreach($arr as $i => $val){
    $arr[$i]="{$val[1]}, {$val[0]}";
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.