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:
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.
3
Answers
You can try to concat the values by changing
to
You could try using
array_map
to get the answers to every question.Then you could use
implode
to join the strings by a delimiter, in this case a","
:Attempt This Online
You can use array_column function
https://onlinephp.io/c/51126