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...?

4
  • See: stackoverflow.com/q/1494953/3933332 Commented Jul 30, 2016 at 11:39
  • stackoverflow.com/questions/12309047/… Commented Jul 30, 2016 at 11:42
  • Guys check it out I want it without any loop..? so it's not duplicate one... please check again @Rizier123, check again don't directly down vote any question Commented Jul 30, 2016 at 11:43
  • @Rizier123 : why still down vote ..? Commented Jul 30, 2016 at 11:47

3 Answers 3

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 ",".

Sign up to request clarification or add additional context in comments.

Comments

1

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

$data = array_column($records, 'country_id');
echo implode(",",$data);

Comments

0

try this,

$newarray = array();

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

i hope it will be helpful.

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.