I have a foreach that is looping over an array as it's supposed to, and then I'm pulling information out of that array from the foreach. I need to put this information into a separate empty array. I've got working, kind of. Here's my code:
newArray = array();
foreach ($result as $value) {
newArray[] = $value['sample1'];
newArray[] = $value['sample2'];
newArray[] = $value['sample3'];
}
print_r(newArray);
This prints an associative array that looks like:
{
0: "1",
1: "1",
2: "blah",
3: "etc through as many values as I have",
}
Instead I need to have it form an array that looks like:
{
0: {
0: "1",
1: "1",
2: "blah"
},
1: {
0: "etc"
}
}
Any recommendations on how I should go about creating the new multidimensional array?
Build a temp array containing the parts of the original you want, then add that temporary array to newArray like this
foreach ($result as $value) {
$t = [ $value['sample1'], $value['sample2'], $value['sample3'] ];
$newArray[] = $t;
}
Or is you are using an old PHP
foreach ($result as $value) {
$t = array( $value['sample1'], $value['sample2'], $value['sample3'] );
$newArray[] = $t;
}
OR shorthand
foreach ($result as $value) {
$newArray[] = [ $value['sample1'], $value['sample2'], $value['sample3'] ];
}
and old PHP
foreach ($result as $value) {
$newArray[] = array( $value['sample1'], $value['sample2'], $value['sample3'] );
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments