wbdlc
wbdlc

Reputation: 1089

PHP: Elegant Way To Output This Array

I'm over complicating the output of this example array, what is the cleanest, most elegant way you would do this for the desired output.

Array Ex:

Array
(
    [0] => Array
        (
            [<h4><a href="#link1">Link 1</a></h4>] => <img src="Image_1.jpg" />
        )

    [1] => Array
        (
            [<h4><a href="#link2">Link 2</a></h4>] => <img src="Image_2.png" />
        )

    [2] => Array
        (
            [<h4><a href="#link3">Link 3</a></h4>] => <img src="Image_3.png" />
        )

    [3] => Array
        (
            [<h4><a href="#link3">Link 4</a></h4>] => <img src="Image_4.png" />
        )
)

Desired Output

<h4><a href="#link1">Link 1</a></h4>
<img src="Image_1.jpg" />

<h4><a href="#link2">Link 2</a></h4>
<img src="Image_2.png" />

<h4><a href="#link3">Link 3</a></h4>
<img src="Image_3.png" />

<h4><a href="#link3">Link 4</a></h4>
<img src="Image_4.png" />

Thanks for the feedback.

Upvotes: 1

Views: 173

Answers (3)

praveen
praveen

Reputation: 1375

I am new to php though i tried my best in bringing up this and i think this would work fine with the sample you provided.

<?php
$link1= '<h4><a href="#link1">Link 1</a></h4>';
$link2= '<h4><a href="#link2">Link 2</a></h4>'; 
$image1='<img src="Image_1.jpg"';
$image2='<img src="Image_2.png"';

$elements =  array("$link1"=>"$image1","$link2"=>"$image2");
foreach($elements as $ele =>$ele_value)
{
echo "link=".$ele . ", image=" . $ele_value;
echo "<br>";
}?>

Upvotes: 0

Ravi Hirani
Ravi Hirani

Reputation: 6539

You can also use array_walk

array_walk($arr, function($value,$key){
        array_walk($value, function($v,$k){
            echo $k;
            echo $v;
       });
});

Upvotes: 1

Gwendal
Gwendal

Reputation: 1273

I think this should do what you want :

<?php

foreach ($foo as $bar) {
    foreach($bar as $title => $image) {
        echo $title;
        echo $image;
    }
}

Upvotes: 6

Related Questions