tags:

views:

96

answers:

9

Hi, I am new to php (learning since 1 week ). I am learning arrays. while doing it, I found a api which gives out results in the form of a multidimensional array.. and I am unable to echo the values of the array ..

Sample response

Array
(
[query] => Array
        (
            [count] => 1
            [created] => 2010-07-16T08:35:38Z
            [lang] => en-US
            [results] => Array
                (
                    [item] => Array
                        (
                            [rel] => rel:Person
                            [resource] => http://twitter.com/twitter
                            [meta] => Array
                                (
                                    [0] => Array
                                        (
                                            [property] => foaf:name
                                            [content] => Twitter
                                        )
                                )
                        )
               )
        )
 )

I can echo some values..like

echo $array["query"]['count']."<br />";   
echo $array["query"]["results"]["item"]["resource"];

but, when I want to use the [meta] => Array

I am not able to use :(

echo $array["query"]["results"]["item"]["resource"]["meta']["0"["content"];

please guide me

+3  A: 

Maybe is because you don't close the ["0"] array properly

echo $array["query"]["results"]["item"]["resource"]["meta"][0]["content"]
Morgen32
Not only the [0], the meta as well.
JochenJung
A: 

If you want to access a numbered item in an array you shouldn't put quotation marks around the number.

Try the following:

 echo $array["query"]["results"]["item"]["resource"]["meta'][0]["content"];

Edit: this answer is incorrect - see comments. Sorry!

Jon
Yes, as Morgen32 says below, you also need the closing square brace on the [0] array reference.
Jon
Nope, PHP doesn't care if you use [0] or ['0'] or even ["0"]. As long as there's an array key that equals what you're requesting, you'll get the value back. And this is the loose equality `==`, not strict equality `===`
Piskvor
its' working even with ["0"]
ramesh
My bad! What's the etiquette here? Delete the response or make an edit to the same effect?
Jon
A: 

don't enclose your numeric index (0) in quotes:

echo $array["query"]["results"]["item"]["resource"]["meta"][0]["content"];

edit: iirc there's a difference between numeric and string indices. nevertheless, the real problem seem to be that you hadn't closed one bracket, and have mixed single/double quotes around meta.

this should have reported and syntax error …

knittl
That doesn't matter, you'll still get the value, no matter if the index is in quotes or not.
Piskvor
but I got the desired output even with ["0"]
ramesh
+2  A: 

From your paste:

[query] => Array (
  [results] => Array (
    [item] => Array (
      [resource] => "http://twitter.com/twitter"
      [meta] => Array (
        [0] => Array (
          [content] => "Twitter"
(...)

The $array["query"]["results"]["item"]["resource"] is not an array, it's a string; you probably want the meta array that's inside $array["query"]["results"]["item"] (same level as resource). This should work:

echo $array["query"]["results"]["item"]["meta"]["0"]["content"];

Also, you made two typos:

  • ["meta'] - you're opening meta with double quote " and trying to close with single quote ' - they have to be the same - e.g. ['meta']
  • ["0" - you didn't close the bracket - e.g. ['0']
Piskvor
+1 The first who noticed that *resource* is a string.
Gumbo
Yeah, good catch +1
Znarkus
+1  A: 

You forgot ] at ["0"]

Also leave out the " around the 0, since you are calling thins elemnt by index, not by name:

$array["query"]["results"]["item"]["resource"]["meta"][0]["content"]

And for meta you used two different kinds of ". One time " and one time '. The closing " needs to be of the same type as the opening one.

JochenJung
A: 

Morgen32 is correct. You hadn't closed the opening [

Also, you can do the same as the "API" you're using is doing by typing

echo "<pre>".print_r($array, true)."</pre>";

below the place in your code that you create the array.

beingalex
+4  A: 

You should use your debugging skills to tackle this kind of problem.

  • First, print_r() your $array, which you did.
  • Then print_r($array['query'])
  • Then print_r($array['query']['results'])
  • and so on, and so on

When you get to print_r($array["query"]["results"]["item"]["resource"]), you see that the result is not an array, it's a scalar, thus you need a different index.

Good luck!

Dennis Haarbrink
Hi, thanks for the sharing this wonderful tip..very helpful.
ramesh
+1 for teaching to fish :)
Piskvor
@Piskvor: Thanks :)
Dennis Haarbrink
+1  A: 
echo $array["query"][count]."<br />";   
echo $array["query"]["results"]["item"]["resource"];

count should be "count", otherwise PHP thinks count is a constant.


echo $array["query"]["results"]["item"]["resource"]["meta']["0"["content"];

"meta' should be "meta", you must use same type of quote.

["0" should be ["0"] or [0] - you must close the bracket.

Znarkus
Thanks for the tip.
ramesh
A: 

Sorry about the length of this post - it is more like a mini-tutorial, but hopefully this should give you some good concepts to play around with which will help you to solve this problem. There is a couple of approaches I would recommend.

Advice #1, when you are using print_r, try using it like so:

print_r ($array[query], 1);

This will allow you to add a 'return' by setting the return flag to true. The advantage of this is that you can embed it like so:

<pre> <?php  echo (print_r($array[query], 1)); ?> </pre> 

This would print a 'pre-formatted' array into your HTML, which would preserve all of the spaces and line breaks. See http://php.net/manual/en/function.print-r.php for more information. I won't go into the full details of how to do this, but there are quite a few tutorials here that will get you started: http://www.java2s.com/Code/Php/Data-Structure/LoopingThroughaMultidimensionalArray.htm (also http://php.net/manual/en/control-structures.foreach.php)

Here is a simple example using the object code from above:

Advice #2. Often I find when I am working with APIs and 'arrays' produced from database results, the type is actually wrong. For example, you will often get something that looks like an array, but is actually a stdObject. Even if this is not the case, I would advise you to try this function (from http://php.net/manual/en/function.var-dump.php):

<?php
$a = array(1, 2, array("a", "b", "c"));
var_dump($a);
?>

Objects and arrays do similar things, but you can avoid notices and possible heartaches by using this approach since var_dump also displays the object type and length. You can try:

<?php
$book = new stdClass;
$book->title = "Harry Potter and the Prisoner of Azkaban";
$book->author = "J. K. Rowling";
$book->publisher = "Arthur A. Levine Books";
$book->amazon_link = "http://rads.stackoverflow.com/amzn/click/0439136369";
?>
<pre>
<?php
    ob_start();
    var_dump($book);
    $a = ob_get_clean();
    $b = print_r($book,1);
    echo($a."\n\n".$b);
?>
</pre>

This also introduces output buffering, which may affect performance, but I have saved may hours of frustration debugging like this (also, you will want to use something like Zend-debug or Xdebug). There is a bit on PHP output buffering with var_dump here: http://stackoverflow.com/questions/139474/how-can-i-capture-the-result-of-var-dump-to-a-string

Aaron Newton
Thanks for the mini tutorial..I leaned some new things :)
ramesh
No problem, HTH ;)
Aaron Newton