I have 3 arrays in PHP that I want to put into one by matching the keys and including new keys for the sub-arrays. I have these arrays:
Array of ID's
{
[0]=> int(1)
[1]=> int(2)
[2]=> int(3)
[3]=> int(4)
[4]=> int(5)
}
Array of Names
{
[1]=> string('Lucas')
[2]=> string('Jorge')
}
Date Array
{
[2]=> string('11 de Mayo')
[3]=> string('7 de Septiembre')
}
DESIRED RESULT
I want to combine them so that they are put in groups by having a match between the keys (the keys). For example Jorge has key 2, so he should go with ID = 2 and Date May 11.
Put keys that indicate what type of data it is (id, name, date).
{
[0]=>
object(stdClass) {
["id"]=> int(1)
},
[1]=>
object(stdClass) {
["id"]=> int(2),
["nombre"]=> string('Lucas')
},
[2]=>
object(stdClass) {
["id"]=> int(3),
["nombre"]=> string('Jorge'),
["fecha"]=> string('11 de Mayo')
},
[3]=>
object(stdClass) {
["id"]=> int(4),
["fecha"]=> string('7 de Septiembre')
},
[4]=>
object(stdClass) {
["id"]=> int(5)
},
}
You can combine the data by doing the following:
$allData
)$tmpArray
), where you put theid
, since there will always be aid
. Then, you search both the names and dates arrays if there is a value with the current key (1,2,3
...), if there is, you add them to$tmpArray
. And then you add$tmpArray
to$allData
.This would be the code:
Proof:
Departure:
To convert it to an object, you can do it once it's created
$allData
, or create it and fill it while it's already an object. I'll leave that to you, it's very easy to do.I hope it helps you.