Convert Two-dimensional String array Separated by comma

Asked

Viewed 35 times

1

I need to convert this Array:

Array
(
[0] => Array
    (
        [value] => pdf
        [label] => PDF
    )
[1] => Array
    (
        [value] => csv
        [label] => CSV
    )
[2] => Array
    (
        [value] => rtf
        [label] => RTF
    )
)

In a String bringing only the label separated by comma. Ex:

PDF, CSV, RTF

I used two foreachs concatenating into a variable and space and comma, and a substr to remove the first comma.

Ex:

foreach ($formatos as $row[label]){
    foreach ($row as $formato => $a){
        $b .= ', '.$a[label];
    }
}
echo $arq = substr($b, 1);

There must be an easier way to do this?

2 answers

2

Surely there is an easier way to concatenate these values into a string:

  • With array_column() get an array containing the values of label.

  • With implode join elements in a string.

<?php

$formatos = [
  [
    'value' => 'pdf',
    'label' => 'PDF'
  ],
  [
    'value' => 'csv',
    'label' => 'CSV'
  ],
  [
    'value' => 'rtf',
    'label' => 'RTF'
  ]
];

$arq = implode(", ", array_column($formatos, 'label'));
echo $arq;  //PDF, CSV, RTF

Test in Repl.it

0

Thank you for the aid Augusto

His reply was excellent.

I had to include the array_combine()

    $formato = array_combine(array_keys($formatos), array_column($formatos, 'label'));
    $arq = implode(", ",$formato);

Decreasing from 6 lines to only 2 and without needing the Gambi of the comma substr($b, 1); ;-)

Browser other questions tagged

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