I'm using
foreach ($objs as $obj) {
$data[] = $obj->getValue;
}
to collect values from a method which may return
array[4]{
[0]=>
string(2) "1234"
[1]=>
string(7) "5678"
[2]=>
string(7) "9ab"
[3]=>
string(10) "cdefg"
...
}
But I need that data in a multidimensional associative array format like...
array[2]{
[0] =>
array[2]{
["alpha"]=>
string(2) "1234"
["beta"]=>
string(7) "5678"
}
[1] =>
array[2]{
["alpha"]=>
string(7) "9ab"
["beta"]=>
string(10) "cdefg"
}
I've been able to do this with two independent loops, one that loops the method data into a two dimensional array, and the second that loops through that array and manually changes the index values to associative values.
$key_labels = array('alpha','beta');
$row_num = $col_num = 0;
$rows = array(
array(),
array()
);
/* Parse the query into a two-dimensional array */
foreach ($objs as $obj) {
$rows[$row_num][$col_num++] = $obj->nodeValue;
if ($col_num == count($key_labels)) {
$col_num = 0;
$row_num++;
}
}
/* Change the array second dimension index values to associative values */
foreach ($rows as $rows_idx => $row) {
unset($rows[$rows_idx]);
foreach ($row as $row_idx => $row_val) {
$rows[$rows_idx][$key_labels[$row_idx]] = $row_val;
}
}
var_dump($rows);
My question is... is there a way to accomplish this more directly than using two verbose (and seemingly clunky) loops? Or is this really the best way?
Note: It is expected that the object will always return a number of rows equal to some even factor of the $key_labels
count.