1

My array is like this. So how can I access the names,values with 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
    )
)

I have tried FOREACH to loop through the array and it does the job, but how can I get their names and values to be used later? My FOREACH code:

foreach($objects AS $values){
    foreach($values as $value){
        echo $value.'<br/>';
    }
}
Wasinha
  • 45
  • 5
  • access the key. `$value['name'];` – Rotimi Mar 25 '18 at 07:02
  • This is actually a bit misleading. What do you mean with `name`? The actual field with that name or the various keys being used? – Mario Mar 25 '18 at 07:07
  • It returns error if I use $values['name'] for example, when I use $values['subject'], an error is "Undefined index: subject in...". – Wasinha Mar 25 '18 at 07:07
  • Yes, I mean the keys and values. – Wasinha Mar 25 '18 at 07:09
  • 1
    Possible duplicate of [PHP - Accessing Multidimensional Array Values](https://stackoverflow.com/questions/17139453/php-accessing-multidimensional-array-values) – Lithilion Mar 25 '18 at 07:11

3 Answers3

1

assume your array is $array:

foreach($array as $item){
       $name = $item['name'];  //extract name
       $value = $item['value'];  //extract value
       echo $name.'  '.$value.'</br>';
}
godot
  • 3,422
  • 6
  • 25
  • 42
0

To get the index/key, just name it:

foreach($collection as $key => $value)
    print($key . ' = ' . $value . '\n');
Mario
  • 35,726
  • 5
  • 62
  • 78
0

Iteration over $objects to get values and names;

foreach($objects as $value){
    echo "Name: ".$value['name'];
    echo " - Value: ".$value['value'];
    echo "<br/>";
}
Karlo Kokkak
  • 3,674
  • 4
  • 18
  • 33
  • Add some details of what the code does, how it works. Code only answers are marked as not helpful. Always try to add some description of the code. – Munim Munna Mar 25 '18 at 08:04