I am attempting to create multidimensional arrays from data in my database whereby each row would be an array. I have attempted this on two different columns with varying results which I'm not sure why.
First Column Loop :
$db_time_qry = "Select Time from Schedule";
$db_time_res = mysqli_query($link, $db_time_qry);
while ($row_c = mysqli_fetch_assoc($db_time_res)) {
$db_times [] = $row_c['Time'];
}
print_r($db_times);
Which returns the following :
Array
(
[0] => 06:00:00
[1] => 06:00:00
[2] => 06:00:00
[3] => 06:00:00
[4] => 06:00:00
[5] => 06:30:00
[6] => 06:00:00
)
Second Column Loop :
$qryDay = ("Select Day from Schedule");
$day_res_ = mysqli_query($link, $qryDay);
while ($row_day_ = mysqli_fetch_assoc($day_res_)) {
if (strlen($row_day_['Day'] == 3)) {
$day_array_ [] = $row_day_['Day'];
} else {
$day_array_ [] = explode(',', $row_day_['Day']);
}
}
print_r($day_array_);
Which results into this :
Array
(
[0] => Array
(
[0] => Wed
)
[1] => Array
(
[0] => Tue
)
[2] => Array
(
[0] => Tue
)
[3] => Array
(
[0] => Thu
)
[4] => Array
(
[0] => Mon
)
[5] => Array
(
[0] => Sun
[1] => Mon
[2] => Tue
)
[6] => Array
(
[0] => Fri
)
)
The second loop returns what I want but why are they returning different results whilst using the same loop? Both arrays have been declared outside of the loops like so : $db_times = $day_array_ = [];
In the first one you're adding values to an array
$array[] = value;
This will just add a single value to an array, so it's one-dimensional.
In the second one explode
will return an array, so your array contains arrays and is two-dimensional.
If you want an array of arrays, you can use
$array[] = array(value);
So the first one would be
$db_times [] = array($row_c['Time']);
and the second
if (strlen($row_day_['Day'] == 3)) {
$day_array_ [] = array($row_day_['Day']);
} else {
$day_array_ [] = explode(',', $row_day_['Day']);
}
You also have an error in your strlen:
strlen($row_day_['Day'] == 3)
This should of course be
strlen($row_day_['Day']) == 3
if you want it to work. Since you're checking strlen
of a boolean, it will never match and always go to the explode
.