PHP访问数组中的元素

时间:2012-03-06 13:31:51

标签: php arrays associative-array

我有一个看起来像这样的数组:

Array
(
    [0] => Array
        (
            [id] => Classify
            [classification] => Array
                (
                    [0] => Array
                        (
                            [class] => negative
                            [p] => 0.0650294
                        )

                    [1] => Array
                        (
                            [class] => positive
                            [p] => 0.934971
                        )

                )

            [text] => Understanding if a text is positive or negative is easy for humans, but a lot harder for computers. We can “read between the lines”, get jokes and identify irony. Computers aren’t quite there yet but the gap is quickly closing in.
        )

)

如何访问positive& negative值?

5 个答案:

答案 0 :(得分:2)

外部数组被数字索引(具有一个元素,一个关联数组),这两个值是数组classification中包含的数组元素的组成部分,数组也是数字索引的,其元素是关联数组

// By iteration, assuming an unknown number of classifications
foreach ($array[0]['classification'] as $classification) {    
  echo $classification['class'];
  echo $classification['p'];
}

// Or direct access to the elements
echo $array[0]['classification'][0]['class']; // negative
echo $array[0]['classification'][0]['p']; // 0.0650294
echo $array[0]['classification'][1]['class']; // positive
echo $array[0]['classification'][1]['p']; // 0.934971

答案 1 :(得分:2)

$array[0]['classification'][0]['p']$array[0]['classification'][1]['p']访问双精度值。

$array[0]['classification'][0]['class']$array[0]['classification'][1]['class']访问“正面”和“否定”字符串

答案 2 :(得分:2)

如果最顶层数组中有多个元素,则必须解析每个元素:

foreach($item in $array)
    foreach($classification in $item['classification'])
        echo $classification['class'];

答案 3 :(得分:1)

print $arr[0]['classification'][0]['class'];
print $arr[0]['classification'][1]['class'];

答案 4 :(得分:1)

print $array[0]['classification'][0]['class'];
print $array[0]['classification'][1]['class'];

如果它总是相同数量的分类......