如何使用php访问多维数组?

时间:2018-03-25 07:01:43

标签: php

我的阵列是这样的。那么如何用php访问名称,值?

Array(
[0] => Array
    (
        [name] => subject
        [value] => คอมพิวเตอร์ ม.3
    )

[1] => Array
    (
        [name] => subject_code
        [value] => ง33101
    )

[2] => Array
    (
        [name] => subject_hour
        [value] => 2
    )

[3] => Array
    (
        [name] => semester
        [value] => 1
    )

[4] => Array
    (
        [name] => level
        [value] => 3
    )

[5] => Array
    (
        [name] => classroom
        [value] => 301
    )

[6] => Array
    (
        [name] => classroom
        [value] => 302
    )
)

我已经尝试过FOREACH循环遍历数组并且它完成了这项工作,但是我怎样才能让他们的名字和值在以后使用? 我的FOREACH代码:

foreach($objects AS $values){
    foreach($values as $value){
        echo $value.'<br/>';
    }
}

3 个答案:

答案 0 :(得分:1)

假设您的数组是$array

foreach($array as $item){
       $name = $item['name'];  //extract name
       $value = $item['value'];  //extract value
       echo $name.'  '.$value.'</br>';
}

答案 1 :(得分:0)

要获取索引/键,只需将其命名为:

foreach($collection as $key => $value)
    print($key . ' = ' . $value . '\n');

答案 2 :(得分:0)

迭代$对象以获取值和名称;

foreach($objects as $value){
    echo "Name: ".$value['name'];
    echo " - Value: ".$value['value'];
    echo "<br/>";
}