-2

我需要一些帮助来读取多维数组中的值。数组如下所示。

Array
(
    [translations] => Array
        (
            [0] => Array
                (
                    [translatedText] => fantasma
                    [detectedSourceLanguage] => en
                )
        )
)

我尝试了以下方法,但不断出现空白。任何帮助表示赞赏?

foreach($item as $translations)
{
       foreach($row['0'] as $k)
       {
             echo $k['translatedText'];
             echo $k['detectedSourceLanguage'];
       }
}
4

4 回答 4

2

使用 foreach 循环时,您希望使用以下语法调用您计划迭代的数组:

foreach($array as $variable){  }

数组是您计划通过的数组,变量是您计划在 foreach 中调用它的变量。

更多关于 foreach 循环的信息可以在PHP:foreach找到

话虽如此,请尝试以下代码:

$data = array(
    "translations" => array(
        array("translatedText" => "fantasma", 
              "detectedSourceLanguage" => "en"
        )
    )
);

echo "<pre>";
echo print_r($data);
echo "</pre>";

foreach($data["translations"] as $translation) {
    echo $translation['translatedText'] . "<br />";
    echo $translation['detectedSourceLanguage'] . "<br />";
}

//Or, if the $data variable will be holding multiple translation arrays:

foreach($data as $d) {
    foreach($d as $translation){
        echo $translation['translatedText'];
        echo $translation['detectedSourceLanguage'];
    }
}
于 2013-07-20T03:17:13.900 回答
0

将您的代码更改为以下:

$test = Array(
    "translations" => Array (
        "0" => Array (
            "translatedText" => "fantasma",
            "detectedSourceLanguage" => "en"
        )
    )
);

foreach ($test as $translations) {
    foreach ($translations as $k) {
        echo $k["translatedText"];
        echo "<br/>";
        echo $k["detectedSourceLanguage"];
    } 
}

这应该有效。

请按照此获取有关数组的更多信息:http: //php.net/manual/en/language.types.array.php

于 2013-07-20T03:15:53.827 回答
0

尝试这个:

foreach ($item['translations'] as $translation) {
  echo $translation['translatedText'];
  echo $translation['detectedSourceLanguage'];
}

演示

于 2013-07-20T03:03:20.800 回答
-1

问题是您没有定义$row变量。好消息是你不需要它。

你可以简单地这样做:

foreach($item as $translations => $values)
{
       foreach($values as $k)
       {
             echo $k['translatedText']."\n";
             echo $k['detectedSourceLanguage'];
       }
}
于 2013-07-20T03:02:48.400 回答