2

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
1
  • 1
    you have to re-design your array. Commented May 2, 2016 at 12:46

4 Answers 4

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

You konow Rising Pune Supergiants team Dhoni, Rishi Bro plz accept Answer .
Frayne relax just kidding in indian style @@
2

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);

Fiddle

answered May 2, 2016 at 12:54

1 Comment

@PedroLobito It would work if you have replaced the shorthand array syntax. Though, OP didn't mention about the version.
1
<?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

1 Comment

Not properly created as OP want.
0

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
answered May 2, 2016 at 13:13

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.