简体   繁体   中英

how to access elements in inside an array?

I combine 4 arrays into a single array named ' questions ' . how to display the elements inside this array one by one?

the PHP code is given below

<?php 
  $questions = array_merge($gk,$english,$malayalam,$maths);
  print_r($questions[1]); 
?>

and the print shows as given below

stdClass Object
(
[question_id] => 18
[question] => chairman of isro
[category_id] => 2
[exam_id] => 0
[subcategory_id] => 0
[category_name] => 
[subcategory_name] => 
[created] => 0000-00-00 00:00:00.00000
[modified] => 0000-00-00 00:00:00.00000
[option_a] => hg
[option_b] => k sivan
[option_c] => hg
[option_d] => fd
[correct_answer] => k sivan
[explanation] => 
)

how to display these items

foreach - is probably the most usable thing for that.

foreach($questions as $question) {
    var_dump($question->question); // "chairman of isro" for the first one
}

As your questions array contain stdClass instances, you can easily display them.

Hope this will help you :

To iterate and print u need foreach loop like this

$questions = array_merge($gk,$english,$malayalam,$maths);
if (! empty($questions))
{
  foreach($questions as $question) {
     echo $question->question_id; /*output 18*/
     echo $question->question; /*output chairman of isro*/
     /*..... all others*/
  }
}

For single question you can do like this :

 $questions[0]->question_id; 
 $questions[0]->question; 

 $questions[1]->question_id; /*output 18*/
 $questions[1]->question; /*output chairman of isro*/

for more : http://php.net/manual/en/control-structures.foreach.php

$questions= json_decode(json_encode($questions), true);

So first of all get your object into array format if you want to handle it as an array (personally i prefer to have it in array than in object format).

You said that your questions have many questions with nested arrays. The only way to access array elements is by using a loop (foreach,whole,for).

So now that your $questions are inside an array you can go like this:

foreach($questions as $row){
    echo $row['question_id'];
    echo $row['question'];
//carry on as you wish.

}

That way you will get access to all your questions and their nested arrays. Inside the foreach you can write your code to handle your data inside the loop, or move some fields to a new array that's up to you.

My answer is based also on your comment to a previous answer about what you want to achieve.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM