Jump to content

Reorder an array's keys but reassociate their index as well??


thepip3r
 Share

Recommended Posts

i have a script reading a CSV file into an array.  sometimes (based on the software version generating the CSV), there are blank cells which result in blank array elements which make the processing off.  i've tried to remove those blank elements using unset() which does work but it doesn't reorder the array:

 

so where i'm expecting $array[20], in the CSV with blank entries, the value i'm looking for is at $array[21] with $array[20] being blank.  using unset, i've been able to wipe out this blank entry but my question is this:  is there an inherent SORT or other function that will reorder the array as well based off of the keys?  i've looked at ksort() etc but they all seem to maintain index association. 

 

i am fine for creating my own, i'd just rather use the PHP version if there is one.  TIA!

 

 

Edit:  let me try to make this a bit more clear:

 

so in my ideal form, the array looks similar to:

    [20] => Monday - November 16, 2009
    [21] => 11/16/2009  12:00
    [22] => 3

 

my problem array looks like:

    [20] => Monday - November 16, 2009
    [22] => 11/16/2009  12:00
    [23] => 3

 

this most recent set is of data is after the unset of the blank field was done on [21].  with this last array, is there a sort function i can pass so that it will reorder the keys so they are in order again with [22] with the date then becomes [21] and so on...

 

does that clear it up?

Link to comment
Share on other sites

The following worked for me

$arr = array("d", "d", "d", "d", "d", "", "", "", "d", "d");
echo count($arr) . "<br />";
$new = array();
foreach($arr as $arr){
if (!empty($arr)){ $new[] = $arr; }
}
echo count($new) . "<br />";
print_r($new);
?>

 

then $new would be the array without the blank values

output:

Array ( [0] => d [1] => d [2] => d [3] => d [4] => d [5] => [6] => [7] => [8] => d [9] => d ) 
10
7
Array ( [0] => d [1] => d [2] => d [3] => d [4] => d [5] => d [6] => d )

 

the important part is the foreach loop

Link to comment
Share on other sites

This thread is more than a year old.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.