I am trying to create an array out of three arrays in the following manner:
$file_data = array();
foreach($file_ids as $key => $id){
foreach($file_names as $name_key => $name){
foreach($file_amounts as $file_key => $cost){
$file_data[] = array("id" => $id, "filename" => $name, "amount" => $cost);
break;
}
break;
}
}
It's creating the first row only. How can I get it to properly assign the values to the $file_data array?
Thanks.
UPDATE: As an example, I have the following for the three arrays
$file_ids[0] = 2;
$file_ids[1] = 4;
$file_name[0] = name1;
$file_name[1] = name2;
$file_amount[0] = 10;
$file_amount[1] = 9;
These arrays will always be of the same size.
What I would like to do is iterate over these arrays and end up with a final array of the form:
$final_array = (id, name, amount)
for all rows in other arrays.
These arrays will always be of the same size.
Just loop to the width of either array:
$final_array = array();
for($i = 0; $i < count($file_name); $i++)
{
$final_array[] = array($file_ids[$i],$file_name[$i],$file_amount[$i]);
}
Make use of array_map
and array_combine
:
$file_ids = array(2, 4);
$file_name = array('name1', 'name2');
$file_amount = array(10, 9);
$result = array_map(null, $file_ids, $file_name, $file_amount);
$keys = array('id', 'filename', 'ammount');
$result = array_map(function($el) use ($keys) {
return array_combine($keys, $el);
}, $result);
echo '<pre>'; print_r($result); echo '</pre>';
Output:
Array
(
[0] => Array
(
[id] => 2
[filename] => name1
[ammount] => 10
)
[1] => Array
(
[id] => 4
[filename] => name2
[ammount] => 9
)
)
Only iterate over one array
$file_ids = array(2,4);
$file_name = array('name1', 'name2');
$file_amount = array(10,9);
$cnt = count($file_ids);
$file_data = array();
for($i = 0; $i < $cnt; $i++){
$file_data[] = array('id' => $file_ids[$i],
'filename' => $file_name[$i],
'amount' => $file_amount[$i]);
}
var_dump($file_data);