0

How to convert array within array to string, that means I am having a one result set having value of country id but the result set will be in array within array.

Something like below code :

Array
(
    [0] => Array
        (
            [country_id] => 7
        )

    [1] => Array
        (
            [country_id] => 8
        )

    [2] => Array
        (
            [country_id] => 9
        )

    [3] => Array
        (
            [country_id] => 10
        )

    [4] => Array
        (
            [country_id] => 1
        )

    [5] => Array
        (
            [country_id] => 2
        )

    [6] => Array
        (
            [country_id] => 3
        )

    [7] => Array
        (
            [country_id] => 4
        )

    [8] => Array
        (
            [country_id] => 5
        )

)

I want that country list into one string like 7,8,9,10,1,2,3,4,5 but without looping..

Anyone have idea please let me know...?

Codebrekers
  • 754
  • 1
  • 11
  • 29

3 Answers3

1

Use array_column and implode for (PHP 5 >= 5.5.0, PHP 7) as

$data = array_column($records, 'country_id');
echo implode(",",$data);
Saty
  • 22,443
  • 7
  • 33
  • 51
1

You can use array_column() and implode() function to do this.

Here is how you can do it,

$values=array_column($array,"country_id");
$country_string=implode($values);

array_column() returns the values from a single column of the input, identified by the column_key(country_id).

implode() returns a string containing a string representation of all the array elements in the same order, with the glue string between each element.


implode() can have two arguments, first as glue by which you want to join the elements and second as the array of elements. If first argument is not given then default glue is ",".

Alok Patel
  • 7,842
  • 5
  • 31
  • 47
0

try this,

$newarray = array();

foreach ($array as $item) {
    $newarray[] = $item['country_id'];
}
echo implode(",",$newarray);

i hope it will be helpful.

Dave
  • 3,073
  • 7
  • 20
  • 33