0

I am trying to read in array values from a csv and create sub-arrays which belong to the primary key field ID. E.g currently, say I have the following array structure & content...

ID;number;product

1;K12;product1

2;157/03/2014;product1

2;;product2

2;product1

3;156/03/2014;product2

3;156/03/2014;product3

I have a php function:

function csv_to_array($file, $delimiter=';')
{
    if(!file_exists($file) || !is_readable($file))
        return FALSE;

    $header = NULL;
    $data = array();
    if (($handle = fopen($file, 'r')) !== FALSE)
    {
        while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
        {
            if(!$header)
                $header = $row;
            else
                $data[] = array_combine($header, $row);
        }
        fclose($handle);
    }
    return $data;
}

Such a result would like to achieve

[1] => Array
    (
        [LP] => 1
        [number] => K12
        [product] => product1
    )
[2] => Array
    (
        Array
            (
                [LP] => 2
                [number] => 157/03/2014
                [product] => product1
            )
        Array
            (
                [product] => product2
            )               
        Array
            (
                [product] => product3
            )

2 Answers 2

1

Replace

data[] = array_combine($header, $row);

With

if(isset($data[$row[0]])) {
$data[$row[0]][] = array_combine($header, $row);
}
else {
$data[$row[0]] = array();
$data[$row[0]][] = array_combine($header, $row);
}
Sign up to request clarification or add additional context in comments.

1 Comment

it works ok, but as it read in the loop? function create($a){ foreach ($a as $date) { } return $output; }
0

Should work:

//$data[] = array_combine($header, $row);
if(isset($data[$row[0]])) {
    array_push($data[$row[0]], array('product' => $row[2]));
} else {
    $data[$row[0]] = array_combine($header, $row);
}

2 Comments

syntax error, unexpected '{' in test.php on line 17: if(isset($data[$row[0]]) {
@damian: yeah, missing )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.