I have this PHP array:-
$tblData[] = array(
"Orange" => "Healthy",
"Apple" => "Good",
"Pizza" => "Bad",
);
This is the output:-
Array
(
[0] => Array
(
[Orange] => Healthy
[Apple] => Good
[Pizza] => Bad
)
)
Now, if I add this:-
$tblData[] = array(
"Hot dogs" => "Big No",
);
This is the output:-
Array
(
[0] => Array
(
[Orange] => Healthy
[Apple] => Good
[Pizza] => Bad
)
[1] => Array
(
[Hot dogs] => Big No
)
)
I want the new key value pair, i.e., "Hot dogs" => "Big No"
to be added under "Pizza" => "Bad"
i.e., under the index [0]
as an item, like this:-
Array
(
[0] => Array
(
[Orange] => Healthy
[Apple] => Good
[Pizza] => Bad
[Hot dogs] => Big No
)
)
I have tried specifying the index, tried array_push
and array_merge
. But, I can’t get it right.
3
Answers
That’s because you have an array inside another array. What you’re doing is adding an element to the outer array, you wish to add it to the inner. You reach the inner array using $tblData[0], so what you need to do is:
You could use any of these methods below in the code, and maybe others also.
Uncomment one of the lines below and test them
They will all generate
You’re currently adding the new entry into the outer array. You need to add it to the inner one (situated at index 0 of the outer array). To do that, simply specify the index of the outer array you want to write to:
Live demo: https://3v4l.org/gcfnI
N.B. This is just one approach, there are several ways to solve it.