0

I am trying to wrap my head around multi dimensional arrays, keys, etc.

I have looked over tons of samples and read over the php docs but I can not get it right.

The sample code below is modified as so it will benefit others and help answer my question.

How do you write the array to store the data and how do you use the foreach loop to build the array so that the array data can be called in a function as shown below.

Here is the array data:

'imgTitle' => "Sample Title A" 
'tabSection' => '0'
'imgId' => '0' 

'imgTitle' => "Sample Title A" 
'tabSection' => '0'
'imgId' => '0' 

'imgTitle' => "Sample TItle B" 
'tabSection' => '0'
'imgId' => '1'

'imgTitle' => "Sample Title C" 
'tabSection' => '0'
'imgId' => '2' 

'imgTitle' => "Sample Title xyz" 
'tabSection' => '1'
'imgId' => '0' 

'imgTitle' => "Sample Title abc" 
'tabSection' => '1'
'imgId' => '1'

'imgTitle' => "Sample Title lmnop"
'tabSection' => '1'
'imgId' => '2' 


function build_img_links() {

    foreach( WHAT_GOES_HERE? ) {
        $output  = '<a href="#">';
        $output .= '<img src="../'.$imgSection.'-'.$imgId.'.jpg"> title="'.$imgTitle.'" />';
        $output .= '</a>';

        return $output;     
    }
}

echo build_img_links(0,1);
echo build_img_links(0,2);
echo build_img_links(1,0);

The paramaters passed above will tie to the array data display.

The output should look like this:

<a href="#"><img src="../0-1.jpg" title="Sample TItle B" />
<a href="#"><img src="../0-2.jpg" title="Sample TItle c" />
<a href="#"><img src="../1-1.jpg" title="Sample TItle abc" />

1 Answer 1

0

Try with:

$data = array(
  array(
    'imgTitle'   => 'Sample Title A',
    'tabSection' => '0',
    'imgId'      => '0' 
  ),
  array(
    'imgTitle'   => 'Sample Title A',
    'tabSection' => '0',
    'imgId'      => '0' 
  ),
  // ....
);

function build_img_links($data) {
  $output = '';

  foreach( $data as $item ) {
    $output .= '<a href="#">';
    $output .= '<img src="../'.$item['imgSection'].'-'.$item['imgId'].'.jpg" title="'.$item['imgTitle'].'" />';
    $output .= '</a>';
  }

  return $output;
}


build_img_links($data);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.