Reputation: 12957
I've following array titled $_FILES
:
Array
(
[document_file_name_2] => Array
(
[name] => FAQ.doc
[type] => application/msword
[tmp_name] => /tmp/phpDnXqMX
[error] => 0
[size] => 35840
)
[document_file_name_5] => Array
(
[name] => Pay Slip-Sushil Kadam-June 2013.pdf
[type] => application/pdf
[tmp_name] => /tmp/php97sAKI
[error] => 0
[size] => 39648
)
)
As this array is generated dynamically it's length may vary. Now what I want to achieve is change some part of existing array key. i want to make the array key start from the key [document_file_name_0]
and so on. The following array should come after doing manipulation. Can anyone help me how should I achieve this? Following is the desired $_FILES
array:
Array
(
[document_file_name_0] => Array
(
[name] => FAQ.doc
[type] => application/msword
[tmp_name] => /tmp/phpDnXqMX
[error] => 0
[size] => 35840
)
[document_file_name_1] => Array
(
[name] => Pay Slip-Sushil Kadam-June 2013.pdf
[type] => application/pdf
[tmp_name] => /tmp/php97sAKI
[error] => 0
[size] => 39648
)
)
Thanks in advance.
Upvotes: 0
Views: 79
Reputation: 17228
I know the best (according to the OP) question is selected, but I'm still eager to say that you could use almost EVERY php loop for this:
foreach() by @RubenSerrate
$newArray=array();
$fileNum=0;
foreach ($originalArray as $file) {
$newArray["document_file_name".$fileNum++]=$file;
}
$newArr = array();
$length = count($_FILES);
for ($i=0; $i<$length; $i++) {
$newArr["document_file_name_".$i] = array_shift($_FILES);
}
$newArr = array();
$i=0;
while ($_FILES) {
$newArr["document_file_name_".$i] = array_shift($_FILES);
$i++;
}
+ all other examples + all other yet not mentioned methods.
Just learn PHP and good luck!
Upvotes: 0
Reputation: 4872
$counter = 0;
foreach ($array as $key => $values) {
if ($key != 'document_file_name_' . $counter) { // If by coincidence this one is correct already, no need to rename/delete the original
$array['document_file_name_' . $counter] = $array[$key];
unset($array[$key]);
}
$counter++;
}
Upvotes: 0
Reputation: 2783
$newArray=array();
$fileNum=0;
foreach ($originalArray as $file) {
$newArray["document_file_name".$fileNum++]=$file;
}
The content of $newArray should be what you're looking for
Upvotes: 1
Reputation: 817
Get the values in the array using array_values
Create a new array and loop through the array_values and set in the new array your custom_key => value pair
Upvotes: 0