morwi
morwi

Reputation: 51

Splitting a column into 3 columns in CSV file, PHP, multidimensional array

I've got a tough task to do I think.

I have a list of products, each and every single one has a specific column which I need to split into 3 columns if they're matching my string

foreach ($csv as $column){
    $match = preg_match("/(?:\d{3}\/\d{2}[R]\d{2})/", $column[5], $matches);
if ($match){
    $split = preg_split("/(?=R)|\//", $matches[0]);
           }
}

So, this is a multidimensional array, first array is a product and inside of each one are its details, which have 18 columns.

What I want to do is extending the array up to 21 columns and only insert split data (if is correct with my string) into column[6][7][8]

if the preg_match isn't correct, just leave [6][7][8] blank and don't touch the [5] column

So:

if !$match
[5] => 150/50ZR40
[6] => empty
[7] => empty
[8] => empty

if $match
[5] => 150/50R40
[6] => 150
[7] => 50
[8] => R40

The [6][7][8] columns already contain different data, so I need to move them further, from 6->9, 7->10 and 8->11 and everything else up to 18->21

edit: the csv is ; separated

Upvotes: 0

Views: 331

Answers (1)

revo
revo

Reputation: 48711

I'm not sure if this code is what you are looking for but it will give you an insight into what you may want to do things. Add capturing groups to your regex:

^(\d{3})/(\d{2})(R\d{2})$

and do a preg_match on it. On TRUE assign values to columns:

if (preg_match("~^(\d{3})/(\d{2})(R\d{2})$~", $column[5], $matches)) {
    /* $matches[0] will contain `150/50R40` */
    array_shift($matches); // removes first element of $matches
    array_splice($column, 6, 0, $matches); // inserts at offset 6
} else {
    // what else you want
}

Upvotes: 1

Related Questions