0

How add a link using the id on comma separated multidimensional array?

What I done so far:

$string = implode(", ", array_column($title_genres, "name"));
echo $string;

My array:

array(4) {
  [0]=>
  object(stdClass)#66 (3) {
    ["id"]=>
    string(2) "21"
    ["name"]=>
    string(8) "Aventure"
    ["tmdb_id"]=>
    string(2) "12"
   }
  [1]=>
  object(stdClass)#67 (3) {
    ["id"]=>
    string(2) "20"
    ["name"]=>
    string(9) "Animation"
    ["tmdb_id"]=>
    string(2) "16"
   }
  [2]=>
  object(stdClass)#63 (3) {
    ["id"]=>
    string(1) "8"
    ["name"]=>
    string(8) "Familial"
    ["tmdb_id"]=>
    string(5) "10751"
   }
  [3]=>
  object(stdClass)#70 (3) {
    ["id"]=>
    string(1) "9"
    ["name"]=>
    string(11) "Fantastique"
    ["tmdb_id"]=>
    string(2) "14"
   }
}
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87

2 Answers2

2

I'd suggest a simple foreach on $title_genres to build a new array of just linked names, then you can do the implode on that to output with commas:

$links = array();
foreach($title_genres as $item) {
    $links[] = '<a href="/some.php?id='. $item['id'] .'">'. $item['name'] .'</a>';
}
echo implode(', ',$links);

Update 1: In case you are using stdClass objects:

$links = array();
foreach($title_genres as $item) {
    $links[] = '<a href="/some.php?id='. $item->id .'">'. $item->name .'</a>';
}
echo implode(', ',$links);

Update 2: An all in one line mash using array_map ;)

echo implode(', ', array_map(function($a){
                        return '<a href="/some.php?id='. $a->id .'">'. $a->name .'</a>';
                   },$title_genres) );
IncredibleHat
  • 4,000
  • 4
  • 15
  • 27
2

Here's the array_map solution, you decide if you consider it simpler than foreach.

$string = implode(",", array_map(function($item) {
    return "<a href='/some.php?id={$item->id'}'>{$item->name}</a>";
}, $title_genres));
echo $string;

If the base URL is in a variable, you can access it using a use() declaration.

$baseurl = base_url();
$string = implode(",", array_map(function($item) use ($baseurl) {
    return "<a href='$baseurl/some.php?id={$item->id'}'>{$item->name}</a>";
}, $title_genres));
Barmar
  • 741,623
  • 53
  • 500
  • 612