Traversing array and separating by commas

Asked

Viewed 159 times

-4

I have an array, and with the var_dump she returns it:

array (size=2)
  0 => 
    array (size=2)
      'id' => int 18
      'name' => string 'Drama' (length=5)
  1 => 
    array (size=2)
      'id' => int 10765
      'name' => string 'Sci-Fi & Fantasy' (length=16)

In what way, can I take only the names from the list and separate them by commas? In this example, I wanted you to stay: Drama, Sci-Fi & Fantasy

  • 1

    Déjà vu: https://answall.com/q/318651/132

  • 1

    @Victorstafusa Oh my! O_O

1 answer

0


You can do it like this:

// array recebido
$array = array(

    array("id"=> 18, "name" => "Drama"),
    array("id"=> 10765, "name" => "Sci-Fi & Fantasy")

);

// string de saída
$string = "";

foreach($array as $valor){
    // adiciona o valor
    $string .= $valor['name'].", ";
}

// retira a ultima vírgula e o espaço
$string = substr($string, 0, -2);

// mostra o resultado
echo $string;
  • 1

    You can take out the window and the final space with $string = rtrim($string, ", ");.

  • 1

    @sam yes! It is that I usually do so. Custom.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.