Reputation: 11
i use preg_match_all and get array like this
Array
(
[1] => Array
(
[0] => link1
[1] => link2
[2] => link3
[3] => link4
[4] => link5
)
[3] => Array
(
[0] => title1
[1] => title2
[2] => title3
[3] => title4
[4] => title5
)
)
I tried using array_merge, but that's not what I wanted
i want the foreach return like this
<a href="link1" class=list-group-item> title1</a>
<a href="link2" class=list-group-item> title2</a>
<a href="link3" class=list-group-item> title3</a>
<a href="link4" class=list-group-item> title4</a>
<a href="link5" class=list-group-item> title5</a>
How can i do that???
Upvotes: 0
Views: 304
Reputation: 26153
To loop two arrays together independent of its indexes use such construction
foreach(array_map(null, ...$arr) as [$link,$title]) {
echo "<a href='$link' class=list-group-item> $title</a>";
Before PHP 7 you need rewrite it to as list($link,$title)
Upvotes: 1
Reputation: 4221
$keys=$array[1];
$values=$array[3];
$combines=array_combine($keys,$values);
foreach($combines as $key=>$value)
{
echo '<a href="'.$key.'" class=list-group-item> '.$value.'</a>';
}
Upvotes: 0
Reputation: 8620
First, reset the keys of your main array.
$array = array_values($array);
Next, loop through one set of your data, in my example I will use the first set of data. Inside the loop, you can grab the 2nd set of data using the key from the first set.
foreach($array[0] as $key => $href) {
$title = $array[1][$key];
echo "<a href='$href' class=list-group-item> $title</a>";
}
This will only work if you always receive 2 sets of data that are the same length.
If you don't want to use that method for whatever reason, you could use array_shift();
.
$links = array_shift($array); //grab first set from array, and remove it from array.
$titles = array_shift($array);
foreach($links as $key => $link) {
$title = $titles[$key];
echo "<a href='$link' class=list-group-item> $title</a>";
}
Upvotes: 6