I have fetch value from database and returning its array in json format. This is my code to get values. First array is working fine. But i need to add static array after every index in array. This is my code
$value = $this->TestModel->get_user_details($userIds);
this function returns array in json format e.g.
[
{
"user_id": "1",
"name": "test 1",
},
{
"user_id": "2",
"name": "test 2",
},
{
"user_id": "3",
"name": "test 3",
},
]
now i need to add below static json array with every item of array. This is e.g
$test1= array("student_list"=> array(array("stu_id"=>1, "name"=> "abc") , array("stu_id"=>2, "name"=> "xyz")),
"class"=> "12th",
"average_score"=>"5",
"results"=>array(array("result_date"=>"2012-12-13","city"=>"city 1"),array("result_date"=>"2015-10-13","city"=>"city 2")));
I have tried it with array_push and array_merge but it add this at the end end of array.
I need this Response
[
{
"user_id": "1",
"name": "test 1",
"student_list": [
{
"stu_id": 1,
"name": "abc",
},
{
"stu_id": 2,
"name": "xyz",
}
],
"class": "12th",
"average_score": "5",
"results": [
{
"result_date": "2012-12-13",
"city": "City 1",
},
{
"result_date": "2012-10-13",
"city": "City 2",
}
]
},
{
"user_id": "2",
"name": "test 2",
"student_list": [
{
"stu_id": 3,
"name": "asd",
},
{
"stu_id": 4,
"name": "ghj",
}
],
"class": "10th",
"average_score": "5",
"results": [
{
"result_date": "2011-12-13",
"city": "City 3",
},
{
"result_date": "2011-10-13",
"city": "City 4",
}
]
},
]
CodePudding user response:
If you want to add $test1
to to every element you your array you should merge each element, like so:
$value = $this->TestModel->get_user_details($userIds);
$test1 = array(
"student_list" => array(array("stu_id" => 1, "name" => "abc"), array("stu_id" => 2, "name" => "xyz")),
"class" => "12th",
"average_score" => "5",
"results" => array(array("result_date" => "2012-12-13", "city" => "city 1"), array("result_date" => "2015-10-13", "city" => "city 2"))
);
$decoded = json_decode($value, true);
for ($i = 0; $i < count($decoded); $i ) {
$decoded[$i] = array_merge($decoded[$i], $test1);
}
$value = json_encode($decoded);