2

I've got associative array with results from database containing data like in following structure:

$arr[0] = Array("id"=>4, "otherdata"=>"something");
$arr[1] = Array("id"=>6, "otherdata"=>"something else");
$arr[2] = Array("id"=>15, "otherdata"=>"something totally different");

I would like to implode data that is only in id key for each $arr entry, so that final imploded string is 4,6,15 (gluded with ,).

Right now I've got some solutions:

  1. Doing it in pure PHP within Smarty.
  2. Creating function that will implode result from array_map which creates new table with id's only.
  3. Assigning variable within Smarty template and creating implode-like result string with foreach.

but neither of them I am happy of.

Is there any other simple way to achieve desired result?

DevilaN
  • 1,317
  • 10
  • 21
  • Unless you are using PHP 5.4 or older, there is no need to use `foreach` or `array_map()`. If you decide to compute the string in PHP then `implode(',', array_column($arr, 'id'))` does what you need. Read about [`array_column()`](http://php.net/manual/en/function.array-column.php). You should probably use a [`{foreach}`](https://www.smarty.net/docs/en/language.function.foreach.tpl) or [`{section}`](https://www.smarty.net/docs/en/language.function.section.tpl) block in Smarty as this belongs to the presentation layer. – axiac Feb 23 '18 at 15:16
  • `foreach` with `rtrim` could be used. https://3v4l.org/bPCPV – user3783243 Feb 23 '18 at 15:16

1 Answers1

11

The 4th solution:

echo implode(',', array_column($arr, 'id'));
u_mulder
  • 54,101
  • 5
  • 48
  • 64