PHP re-organizing an array
Get the solution ↓↓↓The array has to be organized so that, rather than having each value in the array, the array values of arrays with the values of the data, and each of those nested arrays must have a max number of values.
So it should start with this:
$data = array(
0 => 'Data 1',
1 => 'Data 2',
2 => 'Data 3',
3 => 'Data 4',
4 => 'Data 5',
5 => 'Data 6',
);
and then given that$max = 3;
, the array should become this:
$data = array(
0 => array(
0 => 'Data 1',
1 => 'Data 2',
2 => 'Data 3',
),
1 => array(
0 => 'Data 4',
1 => 'Data 5',
2 => 'Data 6',
),
);
I feel like I'm close, but I keep losing the fourth data value when my max is set to 3.
$max_col = 3;
$current_row = 0;
$current_col = 0;
foreach ($data_values as $val) {
if ($current_col < $max_col) {
$new_data[$current_row][$current_col] = $val;
$current_col++;
} else {
$current_col = 0;
$current_row++;
$new_data[$current_row][$current_col] = $val;
}
}
What I end up with is this:
$data = array(
0 => array(
0 => 'Data 1',
1 => 'Data 2',
2 => 'Data 3',
),
1 => array(
0 => 'Data 5',
1 => 'Data 6',
),
);
Answer
Solution:
Have a look at array_chunk
<?php
$data = array(
0 => 'Data 1',
1 => 'Data 2',
2 => 'Data 3',
3 => 'Data 4',
4 => 'Data 5',
5 => 'Data 6',
);
$newData = array_chunk($data, 3);
print_r($newData);
Outputs:
Array
(
[0] => Array
(
[0] => Data 1
[1] => Data 2
[2] => Data 3
)
[1] => Array
(
[0] => Data 4
[1] => Data 5
[2] => Data 6
)
)
Answer
Solution:
Just increment $current_row at the end:
else {
$current_col = 0;
$new_data[$current_row][$current_col] = $val;
$current_row++;
}
Answer
Solution:
your code is almost ok except a minor addition
$max_col = 3;
$current_row = 0;
$current_col = 0;
foreach ($data_values as $val) {
if ($current_col < $max_col) {
$new_data[$current_row][$current_col] = $val;
$current_col++;
} else {
$current_col = 0;
$current_row++;
$new_data[$current_row][$current_col] = $val;
$current_col++; //this is the new line you have to add
}
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: the process class relies on proc_open, which is not available on your php installation.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.