Search code examples
phpsmarty

implode an array of objects and filter only by one property


How I'd implode an array of objects and filter only by one property (category in my case) ?

The object looks like this:

[335] => Array
(
    [category_id] => 335
    [parent_id] => 0
    [category] => Category name
    [aa__aaa00_google_product_category] => 0
)

Here's the current smarty code:

{foreach from=$categories item=category}
   {'| '|implode:$category}
{/foreach}

Solution

  • You can output each category property, then (using last) check whether you're at the last element of the array. If you're not, output a |, otherwise output nothing.

    {foreach from=$categories item=category name=cat}
      {$category.category}{if $smarty.foreach.cat.last}{else}|{/if}
    {/foreach}