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/>';
    }
}
5
  • access the key. $value['name']; Commented Mar 25, 2018 at 7: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? Commented Mar 25, 2018 at 7:07
  • It returns error if I use $values['name'] for example, when I use $values['subject'], an error is "Undefined index: subject in...". Commented Mar 25, 2018 at 7:07
  • Yes, I mean the keys and values. Commented Mar 25, 2018 at 7:09
  • 1
    Possible duplicate of PHP - Accessing Multidimensional Array Values Commented Mar 25, 2018 at 7:11

3 Answers 3

1

assume your array is $array:

foreach($array as $item){
       $name = $item['name'];  //extract name
       $value = $item['value'];  //extract value
       echo $name.'  '.$value.'</br>';
}
Sign up to request clarification or add additional context in comments.

Comments

0

To get the index/key, just name it:

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

Comments

0

Iteration over $objects to get values and names;

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.