2

I have been searching for an answer to a PHP code problem. While it may sound easy to some users, I am having problem below:

I managed to retrieve data from a particular table with PHP and MySql. Unfortunately, I am unable to display result as a string rather than array.

I used print_r($loggedin_users).

Result:

Array ( [0] => Array ( [0] => Test ) [1] => Array ( [0] => Test1 ) )

I have tried using implode function to return me a string.

Result:

ArrayArray

May I know how do I get a result as below?

Desired result:

Test; Test1

Thank you in advance.

Saty
  • 22,443
  • 7
  • 33
  • 51
Enthu
  • 339
  • 2
  • 18
  • To get values from first column use [array_column](http://php.net/manual/en/function.array-column.php): `echo implode("; ", array_column($loggedin_users, 0));` See [test at eval.in](https://eval.in/418610) – Jonny 5 Aug 19 '15 at 08:09
  • Done, your answer helped me alot. Apologies for not accepting earlier. New to Stack Overflow. :) – Enthu Aug 21 '15 at 03:03

4 Answers4

5

The problem is, that you have a two dimensional array. So you are trying to implode two arrays, which can't work. So you first have to implode the subArrays and then implode it again, e.g.

echo implode(";", array_map("implode", $loggedin_users));

Side note:

If you would have error reporting turned on you would have got a notice, saying:

Notice: Array to string conversion

Rizier123
  • 58,877
  • 16
  • 101
  • 156
  • 2
    Ah, precisely why I am not getting it right at all. I will read more on two dimensional array. Your code has fixed the problem and I appreciate your time in looking into the issue. – Enthu Aug 19 '15 at 07:02
2

You can use array_reduce():

echo array_reduce($array, function($carry, $item) {
    if(is_null($carry)) {
        return $item[0];
    } else {
        return $carry . "; " . $item[0];
    }
});
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
0

Use foreach them use implode because you have multidimensional array.

foreach($loggedin_users as $key => $val){
  $string = implode(', ', $val);
}
aldrin27
  • 3,407
  • 3
  • 29
  • 43
0

You have to create a recursive function here. so, no matter what array it is and no matter upto what extent that is nested. you'll always get desired result.

$a = array(
 0 => array(0 => 'Test'),
 1 => array(0 => 'Test1')
);

function implodeCustom($array){
    $string = "";
    foreach($array as $key => $value)
    if(is_array($value)){
        $string .= implodeCustom($value);
    } else{
        $string .= $value.";";
    }
    return $string;
}

echo rtrim(implodeCustom($a),';');
rawat0419
  • 136
  • 9