2

I'm having problems with matching up different array values to other array keys. Here's my array:

array(3){
  [0]=>array(3){ //image number (mainly used for image display order)
    [0]=>string(1)"1"
    [1]=>string(1)"2"
    [2]=>string(1)"3"
  }
  [1]=>array(3){ //image link
    [0]=>string(8)"img1.jpg"
    [1]=>string(8)"img2.jpg"
    [2]=>string(8)"img3.jpg"
  }
  [2]=>array(3){ //thumbnail link
    [0]=>string(10)"thumb1.jpg"
    [1]=>string(10)"thumb2.jpg"
    [2]=>string(10)"thumb3.jpg"
  }
}

I'm using smarty, here's my code:

{foreach from=$CARIMGS item=newArr}
   {foreach from=$newArr key=index item=item}               
      {$item} <br>      
   {/foreach}
{/foreach}

Here's what I get now:

1
2
3
img1.jpg
img2.jpg
img3.jpg
thumb1.jpg
thumb2.jpg
thumb3.jpg

And I need to get this result:

1 - img1.jpg - thumb1.jpg
2 - img2.jpg - thumb2.jpg
3 - img3.jpg - thumb3.jpg

Thanks in advance!

Tatarin
  • 1,238
  • 11
  • 28

2 Answers2

1

The best thing to do would be to prepare the datastructure in a more usable format before giving it to Smarty:

$forSmarty = array();

// loop over the array with the image link since its the most significant piece of data
// and the other items shouldnt exist without a corresponding image link
foreach($arr[1] as $i => $link) {
   $forSmarty[] = array(
      'img' => $link,
      'thumb' => isset($arr[0][$i]) ? $arr[0][$i] : null,
      'position' => isset($arr[2][$i]) ? (int) $arr[2][$i] : 0,
   );
}

// lets sort by position
usort($forSmarty, function ($a,$b) {
   if ($a['position'] == $b['position']) {
        return 0;
    }
    return ($a['position'] < $b['position']) ? -1 : 1;
});

Then you would set $forSmarty as CARIMGS on the Template and loop like so (not sure if i have the right notation syntax for array elements/object properties, so adjust as needed):

{foreach from=$CARIMGS item=carimg}     
      {$carimg.position} - ${carimg.img} - ${carimg.thumb}<br />      
{/foreach}
prodigitalson
  • 60,050
  • 10
  • 100
  • 114
  • WOW! I tried to understand your solution and start making my own, based on your idea. Eventually, I reached the point of what you did and did the same. Best solution by far. – Tatarin Aug 19 '13 at 16:11
0

You can zip the arrays together like here : Is there a php function like python's zip?.

But this works correctly if they have the same length.

Let's say that array of arrays you want to print is $list.

Then you can do $list = array_map(null, $list[0], $list[1], $list[2]); to get what you want.

If you want the dashes you can like this:

$dashes = array(' - ', ' - ', ' - ');
$list = array_map(null, $list[0], $dashes, $list[1], $dashes, $list[2]);

And now you have for each row an array, to get a single string you can map the implode

$list = array_map(implode, $list);

Only 3 lines of code to prepare everything. Hope it helps.

Community
  • 1
  • 1
adrian.budau
  • 349
  • 1
  • 6