I am having issues with a php loop.
Perhaps there is a better way to do this. Currently my post
is returning
array(4) {
[1]=> string(2) "on"
["1-qty"]=> string(1) "1"
[5]=> string(2) "on"
["5-qty"]=> string(1) "9"
}
I am trying to make a new array of 2 arrays such as the following
array(2) {
array(2) {
[category]=> string(2) "1"
["qty"]=> string(1) "1"
}
array(2) {
[category]=> string(2) "5"
["qty"]=> string(1) "9"
}
}
I have tried about every foreach and for loop that I can manage to put together. The main problem being the first value I need is the key not the value of the first array. Then I need to take the first two arrays from the main array and add to a new array with the first array key being the new value of the first key category in the array, and the value of the second array being the value of the new key qty in the array, and repeat by groups of 2 foreach set that is in the post
variable
Current loop (not working)
$data = $this -> input -> post();
$dCount = count($data);
$newCount = $dCount / 2;
$fin = array();
for ($i = 0; $i <= $newCount; $i++) {
$vals = array_slice($data, 0, $i + 1, true);
$qty = array_slice($vals, 0, $i , true);
$key = current(array_keys($qty));
$final = array('category' => $key, 'qty' => $qty[$key . '-qty']);
$fin[] = $final;
}
Try this way:
$source_arr = array(1 => "on", "1-qty" => 1, 5 => "on", "5-qty" => "9");
$result_arr = array();
foreach ($source_arr as $key => $value) {
if ($value == "on" && isset($source_arr[$key . "-qty"])) {
$result_arr[] = array(
'category' => $key,
'qty' => $source_arr[$key . "-qty"]
);
}
}