Reputation: 2306
I'm starting with a csv variable of column names. This is then exploded into an array, then counted and tossed into a for loop that is supposed to create another array.
Every time I run it, it goes into this endless loop that just hammers away at my browser...until it dies. :(
Here is the code..
$columns = 'id, name, phone, blood_type';
$column_array = explode(',',$columns);
$column_length = count($column_array);
//loop through the column length, create post vars and set default
for($i = 0; $i <= $column_length; $i++)
{
$array[] = $iSortCol_.$i = $column_array[$i];
//create the array iSortCol_1 => $column_array[1]...
//$array[] = 'iSortCol_'.$i = $column_array[0];
}
What I would like to get out of all this is a new array that looks like so..
$goal = array(
"iSortCol_1" => "id",
"iSortCol_2" => "name",
"iSortCol_3" => "phone",
"iSortCol_4" => "blood_type"
);
Upvotes: 1
Views: 172
Reputation: 73292
Simply change
$array[] = 'iSortCol_'.$i = $column_array[0];
to
$array['iSortCol_'.$i] = $column_array[$i];
and the <=
to <
in your for
loop, otherwise you will display a blank array value in your end result. Because you need to go up to but not including the length of $column_array
.
Upvotes: 2
Reputation: 50019
$array[] = 'iSortCol_'.$i = $column_array[0];
I think it's because you're assigning the value of $column_array[0] to $i AND using it as the loop index. Use another variable to do that, otherwise it just goes on and on.
EDIT Tested and pasted output
Working code, just tested it on local
$columns = 'id, name, phone, blood_type';
$column_array = explode(',',$columns);
$column_length = count($column_array);
$array = array();
for($i = 0; $i < $column_length; $i++)
{
//create the array iSortCol_1 => $column_array[1]...
$array['iSortCol_'.$i] = $column_array[$i];
}
var_dump($array);
This will output
array
'iSortCol_0' => string 'id' (length=2)
'iSortCol_1' => string ' name' (length=5)
'iSortCol_2' => string ' phone' (length=6)
'iSortCol_3' => string ' blood_type' (length=11)
Is this not what you want?
Upvotes: 1
Reputation: 116110
I think you meant to write:
$array['iSortCol_'.$i] = $column_array[0];
Upvotes: 0