I'm having an array "pollAnswers" which displays:
Array
(
[0] => Sachin
[1] => Dhoni
)
in PHP and I want it to display as:
"pollAnswers":[
{"pollAnswersID":0, "pollAnswer":"Sachin"},
{"pollAnswersID":1, "pollAnswer":"Dhoni"}
]
in JSON output.
I've tried using array_fill_keys and array_flip but that's not solution for this. It seems I need to split the array_keys and array_values and then do some concatenation to get this, but I'm stuck here!
asked May 2, 2016 at 12:43
Rishi Kulshreshtha
1,9081 gold badge27 silver badges38 bronze badges
-
1you have to re-design your array.Murad Hasan– Murad Hasan2016年05月02日 12:46:17 +00:00Commented May 2, 2016 at 12:46
4 Answers 4
Online check link
Try this
$arr = array("Sachin", "Dhoni");
$sub_arr = array();
$final = array();
foreach($arr as $key => $val){
$sub_arr['pollAnswersId'] = $key;
$sub_arr['pollAnswer'] = $val;
$sub_final[] = $sub_arr;
}
$final['pollAnswers'] = $sub_final;
echo json_encode($final);
result
{"pollAnswers":[
{"pollAnswersId":0,"pollAnswer":"Sachin"},
{"pollAnswersId":1,"pollAnswer":"Dhoni"}
]}
answered May 2, 2016 at 12:54
Murad Hasan
9,5932 gold badges23 silver badges43 bronze badges
You can try with array_map.
$Array = array('Sachin', 'Dhoni');
$new = array_map(function($v, $k) {
return ['pollAnswersId' => $k, 'pollAnswer' => $v]; // return the sub-array
}, $Array, array_keys($Array)); // Pass the values & keys
var_dump(json_encode(array("pollAnswers" => $new)));
Output
"{"pollAnswers":[
{"pollAnswersId":0,"pollAnswer":"Sachin"},
{"pollAnswersId":1,"pollAnswer":"Dhoni"}
]}"
For older versions of PHP.
return array('pollAnswersId' => $k, 'pollAnswer' => $v);
answered May 2, 2016 at 12:54
Sougata Bose
31.8k8 gold badges52 silver badges89 bronze badges
1 Comment
Sougata Bose
@PedroLobito It would work if you have replaced the shorthand array syntax. Though, OP didn't mention about the version.
<?php
$answerArray = [];
foreach($yourArray as $key => $r)
$answerArray[] = ['pollAnswersId' => $key, 'pollAnswer' => $r];
echo json_encode($answerArray);
Here you go.
answered May 2, 2016 at 12:45
LoïcR
5,0371 gold badge37 silver badges53 bronze badges
1 Comment
Murad Hasan
Not properly created as OP want.
Try this:
$givenArray = array("Sachin","Dhoni");
$answerArray = [];
foreach($givenArray as $key => $r)
$answerArray[] = ['pollAnswersId' => $key, 'pollAnswer' => $r];
echo $out = json_encode(array('pollAnswers' => $answerArray));
Aaron Christiansen
12k7 gold badges59 silver badges82 bronze badges
Comments
lang-php