Reputation: 39
I want to display multiple arrays into one such that each time the object is created it get a key value and then forms a object to be more specific following is a short example.
How it is now:
name:[{},{},{},{}]
surname:[{},{},{},{}]
phone: [{},{},{},{}]
How I want it to be:
xyz:[{name:{}, surname{}, phone{}},
{name:{}, surname{}, phone{}},
{name:{}, surname{}, phone{}}]
I am exporting this in php so that I can use this JSON object in AngularJs ng-repeat directive.
following is the code:
declaring array:
$name = array();
$surname= array();
$phone= array();
assigning values WHICH IS UNDER FOR EACH LOOP
$name[] = $values ($values wil have the values for the loop)
.....
testing output
<?php echo json_encode($name);
echo json_encode($surname);
echo json_encode($phone);
?>
Upvotes: 2
Views: 1122
Reputation: 6217
A simple way of doing it (run):
$name = array("name 1", "name 2");
$surname = array("surname 1", "surname 2");
$phone = array("phone 1", "phone 2");
$output = array();
for($i = 0; $i < count($name); $i++){
$output[] = array(
'name' => $name[$i],
'surname' => $surname[$i],
'phone' => $phone[$i],
);
}
print_r($output);
Output:
Array
(
[0] => Array
(
[name] => name 1
[surname] => surname 1
[phone] => phone 1
)
[1] => Array
(
[name] => name 2
[surname] => surname 2
[phone] => phone 2
)
)
Note: It assumes all arrays are of same size and have same keys.
But maybe it would be better to instead of saving each value to 3 different variables and then running this script, try saving the values already into the array as the desired output (if possible, of course, since we can't know).
Upvotes: 1