86Stang
86Stang

Reputation: 349

Cleaning up certain sections of an array

Im using the following code to import a csv that has two columns - account & phone:

$csv = array();
$file = fopen('import.csv', 'r');

while (($result = fgetcsv($file)) !== false)
{
    $csv[] = $result;
}

fclose($file);

The results look something like:

Array
(
    [0] => Array
        (
            [0] => 5182334
            [1] => (360) 293-7786
        )

    [1] => Array
        (
            [0] => 8372855
            [1] => (360) 755-3237
        )

    [2] => Array
        (
            [0] => 8373250
            [1] => (360) 873-8853
        )

    [3] => Array
        (
            [0] => 8373226
            [1] => (360) 588-1905
        )
)

What I need to do is loop through the array and clean up the phone numbers removing spaces, parans, etc. I know how to do the clean up but can't figure out how to loop through the array to do said cleaning.

Upvotes: 0

Views: 73

Answers (3)

Jakub Truneček
Jakub Truneček

Reputation: 8990

You can use array_map and preg_replace for example.

function clean($item) {
   $item[1] = preg_replace('#[^\d]#', '', $item[1]);
   return $item;
}

$csv = array_map("clean", $csv);

Or directly in loading phase:

$csv = array();
$file = fopen('import.csv', 'r');

while (($result = fgetcsv($file)) !== false)
{
    $result[1] = preg_replace('#[^\d]#', '', $result[1]);
    $csv[] = $result;
}

Upvotes: 3

mychalvlcek
mychalvlcek

Reputation: 4046

$search = array(' ', '-', '(', ')'); 
foreach($csv as &$line) {
    $line[1] = str_replace($search, '', $line[1]);
}

Upvotes: 0

Teena Thomas
Teena Thomas

Reputation: 5239

Try:

$arr = array(....); //your array
//Removing '(', ')', ' ' and '-' from the array values.
foreach($arr as $v)
 $v = str_replace(array(' ', '(', ')', '-'), '', $v);

Upvotes: 0

Related Questions