开发者

Multi Dimensional arrays in php

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


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!


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

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


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']


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.


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.


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.


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://www.amazon.com/dp/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: How can I capture the result of var_dump to a string?


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 …

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜