Chris
Chris

Reputation: 301

PHP for echos an array

I am having trouble trying to echo each iteration of a particular part of an array.

Here are the clues. I can't quite piece them together (since I don't yet know much about php arrays).

If I do the following:

<?php
$audiofile = simple_fields_value("audiofile");
echo $audiofile['url'];
?>

I get the URL of the file, which is what I want. However, I have four different URL's (A "two-dimensional array", I believe?), and I want to echo each of them.

According to the Simple Fields documentation, I know that I need to change the second line to:

$audiofile = simple_fields_values("audiofile");

This leads me to change the php as follows:

<?php
$audiofile = simple_fields_values("audiofile");
for($i=0;$i<count($audiofile);$i++)
{
echo $audiofile[$i];
}
?>

But this only echoes "ArrayArrayArrayArray".

Which makes sense, because $audiofile is returning an array of info, FROM WHICH I only want the ['url'].

So, I tried the following:

<?php
$audiofile = simple_fields_values("audiofile");
for($i=0;$i<count($audiofile);$i++)
{
echo $audiofile['url'][$i];
}
?>

But that echoes null.

Any ideas?

Upvotes: 0

Views: 133

Answers (3)

fntlnz
fntlnz

Reputation: 411

Why not with a foreach construct?

$audiofile = simple_fields_values("audiofile");
foreach ($audiofile as $key => $value) {
    echo $audiofile[$key]['url'];
}

It's more handful than a for cycle, basically you haven't to count items and increment the index by yourself because foreach has been built ad hoc to iterate over php arrays.

http://php.net/manual/en/control-structures.foreach.php

Upvotes: 0

Andrew
Andrew

Reputation: 2011

You can either do:

<?php
$audiofile = simple_fields_values("audiofile");
for($i=0;$i<count($audiofile);$i++)
{
    print_r($audiofile[$i]);
}
?>

or do a var_dump

<?php
$audiofile = simple_fields_values("audiofile");
for($i=0;$i<count($audiofile);$i++)
{
    var_dump($audiofile[$i]);
}
?>

Upvotes: 0

Will
Will

Reputation: 2333

I think you may have your array key order backwards is all. Have you tried flipping ['url'][$i] into [$i]['url']? Like this:

<?php
$audiofile = simple_fields_values("audiofile");
for($i=0;$i<count($audiofile);$i++) {
    echo $audiofile[$i]['url'];
}
?>

Upvotes: 5

Related Questions