Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating an associative array in PHP

I am a beginner to Programming; I am stuck while creating an associative array from an existing associative array

<?php
    $arr = array( 
            array(
                "question"=>"I get irritated easily.",
                "answer"=>"1"
            ),
            array(
                "question"=>"I spend time reflecting on things.",
                "answer"=>"1"
            ),
            array(
                "question"=>"I am quiet around strangers.",
                "answer"=>"1"
            ),
            array(
                "question"=>"I make people feel at ease.",
                "answer"=>"1"
            ),
            array(
                "question"=>"I am exacting in my work.",
                "answer"=>"1"
            ),
            array(
                "question"=>"I often feel blue.",
                "answer"=>"3"
            ),
            array(
                "question"=>"I am full of ideas.",
                "answer"=>"4"
            )
        );
     
     
     $answer_array = array();
     foreach( $arr as $questions ) {
       $answer_array['text']=$questions['answer'];
     }
     print_r( $answer_array );
?>

I want the $answer_array in the following format:
$answer_array("text"=>"1 , 1 , 1 , 1 , 1 ,3 , 4")

But I am not getting the correct answer as it displays in the following manner:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Array
(
    [text] => 4
)

This is because it overwrites all the other values while iterating and only stores the last value. I need to store all the value as I have mentioned above. Kindly suggest where am I going wrong.

>Solution :

You can try to concat the values by changing

 $answer_array['text']=$questions['answer'];

to

if(isset($answer_array['text'])){
  $answer_array['text'] .= ', '. $questions['answer'] ;
} else {
 $answer_array['text'] = $questions['answer'];
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading