CodeIgniter Forums

Full Version: looping throug multiple arrays
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

[eluser]Tazz[/eluser]
Hi guys

I have a database which contains the names of images and their names(or comments).
Using a sql query I pull the contents of the table and it's put into an array for each row.

For example, I have 3 arrays all with an ID, Name and a Path.

array(3) {
[0]=> array(3) { ["ID"]=> string(1) "1" ["Name"]=> string(4) "PicOne" ["Path"]=> string(8) "One.jpg" }
[1]=> array(3) { ["ID"]=> string(1) "2" ["Name"]=> string(7) "PicTwo" ["Path"]=> string(8) "Two .jpg" }
[2]=> array(3) { ["ID"]=> string(1) "3" ["Name"]=> string(4) "PicThree" ["Path"]=> string(9) "Three.jpg" }
}

These I get from my database using a SQL query.

How do I loop through all the returned arrays and only extract their ['Path']? I want to use it then in a <img src='".$path."'/> to dynamically populate my page full of the images extracted from the database.


I have tried many different ways Including this one :

$i = 0;
while ($i <= count($Array)) {
print "$Array[i]<br>";
$i++;

But none seems to work. All I need is to extract the ['Path'] from each array that I receive from my SQL query. Anyone know of a way?

El Forum

[eluser]bigtimslim[/eluser]
This is from the user guide. You could modify for your needs.
Code:
foreach ($query->result() as $row)
{
    echo $row->title;
}

El Forum

[eluser]Yash[/eluser]
I guess too simple let me try it
Code:
array(3) {
[0]=>  array(3) { [“ID”]=>  string(1) “1” [“Name”]=>  string(4) “PicOne” [“Path”]=>  string(8) “One.jpg” }
[1]=>  array(3) { [“ID”]=>  string(1) “2” [“Name”]=>  string(7) “PicTwo” [“Path”]=>  string(8) “Two .jpg” }
[2]=>  array(3) { [“ID”]=>  string(1) “3” [“Name”]=>  string(4) “PicThree” [“Path”]=>  string(9) “Three.jpg” }
}

//arr = array(3)

for($i=0;<$i<count($arr);$i++)
{
         echo arr[$i]['Path'];
}

Try this ..

El Forum

[eluser]Tazz[/eluser]
Thanks Yash, what you suggested works perfectly.

I modified it sligthly :

for($i=0; $i < count($Array); $i++)
{
echo $Array[$i]['Path'];
//this spits out only the path of the image
}

El Forum

[eluser]xwero[/eluser]
A tip : never put function calls in the second part of a for loop because they will be called with each iteration.
Code:
for($i=0,$max=count($arr);$i<$max;$i++)
If you put this loop in your view file you can use the foreach loop for better readability.
Code:
foreach($pictures as $picture)
{
   echo $picture['path'];
}