Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through array and output links based on number of arrays

I currently have an array as follows:

   Array ( 
    [0] => Array ( [id] => 34 [another_id] => 2805 [third_id] => 1 ) 
    [1] => Array ( [id] => 35 [another_id] => 2805 [third_id] => 1 ) 
    [2] => Array ( [id] => 36 [another_id] => 2805 [third_id] => 1 ) 
    [3] => Array ( [id] => 37 [another_id] => 2805 [third_id] => 1 ) 
    [4] => Array ( [id] => 38 [another_id] => 2805 [third_id] => 1 ) 
    [5] => Array ( [id] => 39 [another_id] => 2805 [third_id] => 1 ) 
    [6] => Array ( [id] => 40 [another_id] => 2805 [third_id] => 2 ) 
    [7] => Array ( [id] => 41 [another_id] => 2805 [third_id] => 2 )
    [8] => Array ( [id] => 42 [another_id] => 2805 [third_id] => 2 ) 
    [9] => Array ( [id] => 43 [another_id] => 2805 [third_id] => 2 )
 )

What I need to do is ultimately print out 9 links ( as there are 9 array elements) but based on the keys in the array. For example:

www.samplelink/link/id/another_id/third_id

But I can't seem to get the loop right. What I have so far is:

foreach ($array as $arr) {
  foreach ( $arr as $key => $value ) {
    echo "<a>www.samplelink/link/".$key[$value]."</a>";
  }
}

But thats not exactly what I need as its printing out the keys as well. Anyone know what I could do?

like image 966
user Avatar asked Dec 05 '25 14:12

user


2 Answers

 foreach ($array as $innerArray) {
  echo "<a>www.samplelink/link/".$innerArray['id']."/".$innerArray['another_id']."/".$innerArray['third_id']."</a>";
 }

It can give an undefined index error if key doesn't exist so you can do something like this as well:

foreach ($array as $innerArray) {
    $finalLink = array_key_exists('id',$innerArray)?$innerArray['id']:"";
    $finalLink.= "/".array_key_exists('another_id',$innerArray)?$innerArray['another_id']:"";
    $finalLink.= "/".array_key_exists('third_id',$innerArray)?$innerArray['third_id']:"";
    echo "<a>www.samplelink/link/$finalLink</a>";
}
like image 120
Danyal Sandeelo Avatar answered Dec 08 '25 04:12

Danyal Sandeelo


If elements in subarrays always in same order, you can just implode them:

foreach ($array as $arr) {
    echo "<a>www.samplelink/link/".implode('/', $arr)."</a>";
}

Otherwise you should point what index will be in which position explicitly, as in @Danyal Sandeelo's answer.

like image 24
u_mulder Avatar answered Dec 08 '25 02:12

u_mulder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!