无法从Mongo转储中获取数据

时间:2023-02-04 10:44:58

Below is the dump that I got from mongo. I need to fetch the opening artist name.

下面是我从mongo获得的转储。我需要获取开场艺术家的名字。

Array
(
[_id] => MongoId Object
    (
        [$id] => 51c9b63b6f7cb5f8229f27b7
    )

[s20] => Array
    (
        [opening] => Array
            (
                [artist] => Array
                    (
                        [name] => Jay Z
                    )

                [music] => Array
                    (
                        [name] => 99 problems
                    )

            )
)

So, I tried:

所以,我尝试过:

foreach($mongo_dump as $key=>$value){
    echo "<pre>KEY: " . print_r($key["s20"]["opening"]["artist"]["name"]) . "</pre>";   // line # 16
    echo "<pre>VALUE: " . print_r($value) . "</pre>";
    echo "\n\n";
}

However, I did not get the artist name. I received the following PHP warning:

但是,我没有得到艺术家的名字。我收到了以下PHP警告:

PHP Warning:  Illegal string offset 's20' in /var/www/Code/analytics/fetch_top_5_opening_artists.php on line 16

2 个解决方案

#1


2  

As Blaine mentions, $key isn't an array. The way that you are traversing the dump is incorrect. $key becomes a string in the context of the foreach loop. Try doing something like this:

正如Blaine所提到的,$ key不是一个数组。遍历转储的方式不正确。 $ key成为foreach循环上下文中的字符串。尝试做这样的事情:

if ($key == "s20") {
   echo "<pre>KEY: " . print_r($value["opening"]["artist"]["name"]) . "</pre>";
}

#2


0  

the value itself is array() so your forloop is not going work unless you setupup nested. Here is example of neted for loop.

值本身是array()所以除非你设置嵌套,否则你的forloop不会工作。这是neted for循环的例子。

foreach($mongo_dump as $key )
{

  { 
  foreach($key as $subkey) 
   {

    echo $subkey
    echo "\n\n";
 }

}

#1


2  

As Blaine mentions, $key isn't an array. The way that you are traversing the dump is incorrect. $key becomes a string in the context of the foreach loop. Try doing something like this:

正如Blaine所提到的,$ key不是一个数组。遍历转储的方式不正确。 $ key成为foreach循环上下文中的字符串。尝试做这样的事情:

if ($key == "s20") {
   echo "<pre>KEY: " . print_r($value["opening"]["artist"]["name"]) . "</pre>";
}

#2


0  

the value itself is array() so your forloop is not going work unless you setupup nested. Here is example of neted for loop.

值本身是array()所以除非你设置嵌套,否则你的forloop不会工作。这是neted for循环的例子。

foreach($mongo_dump as $key )
{

  { 
  foreach($key as $subkey) 
   {

    echo $subkey
    echo "\n\n";
 }

}