Home > Software engineering >  set fixed string value until next detected change in foreach php
set fixed string value until next detected change in foreach php

Time:11-29

I have a CSV with data like this: (for some reason table doesn't display properly after I publish question, so here is screenshot from question edit screen) CSV Im trying to convert it into array to have data like this:

Array
(
    [0] => Array
        (
            [code] => PRODUCTID1
            [name] => HONDA
            [country] => JAPANESE
        )

    [1] => Array
        (
            [code] => PRODUCTID2
            [name] => TOYOTA
            [country] => JAPANESE
        )

    [2] => Array
        (
            [code] => PRODUCTID3
            [name] => NISSAN
            [country] => JAPANESE
        )

    [3] => Array
        (
            [code] => PRODUCTID4
            [name] => BMW
            [country] => GERMAN
        )

    [4] => Array
        (
            [code] => PRODUCTID5
            [name] => AUDI
            [country] => GERMAN
        )

    [5] => Array
        (
            [code] => PRODUCTID6
            [name] => MERCEDES
            [country] => GERMAN
        )
)

How do I set $country string to be same for every line until next detected change?

Obviuosly putting this inside foreach loop doesn't work as it searches and sets value on every line:

if (strpos(strtolower(trim($value[1])), 'japanese') === true) {
    $country = 'japanese';
}
elseif (strpos(strtolower(trim($value[1])), 'german') === true) {
    $country = 'german';
}

this is my code:

function csv_content_parser($content) {
  foreach (explode("\n", $content) as $line) {
    yield str_getcsv($line, ",");
  }
}

$content = file_get_contents('cars.csv');

// Create one array from csv file's lines.
$data = array();
foreach (csv_content_parser($content) as $fields) {
  array_push($data, $fields);
}

$naujas_array = array();

foreach ($data as $key => $value) {

    if (!empty($value[0])) {
            $naujas_array[] =  array(
            'code'              => $value[0], 
            'name'              => $value[1], 
            'country'           => $country);
    }   
}
print_r($naujas_array);

CodePudding user response:

Start with an empty $country, and if $value[0] is empty, change it:

$country = null;

foreach ($data as $key => $value) {

    if (!empty($value[0])) {
            $naujas_array[] =  array(
            'code'              => $value[0], 
            'name'              => $value[1], 
            'country'           => $country);
    } else {
        $country = $value[1];
    }
}

CodePudding user response:

You don't need the extra foreach() loop to push data from your generator into the temporary $data array.

Loop over your generator data and destructure each row into intuitive variables ($code and $name).

Use a functionless condition to determine if the $code value is empty. If so, cache the $name value as the $country. If not, form an associative row with compact() and push that data into the result array.

Code: (Demo)

$result = [];
$country = null;
foreach (csv_content_parser($content) as [$code, $name]) {
    if (!$code) {
        $country = $name;
    } else {
        $result[] = compact(['code', 'name', 'country']);
    }
}
var_export($result);

Or continue to avoid the else branch and minimize code tabbing/width. (Demo)

$result = [];
$country = null;
foreach (csv_content_parser($content) as [$code, $name]) {
    if (!$code) {
        $country = $name;
        continue;
    }
    $result[] = compact(['code', 'name', 'country']);
}
var_export($result);
  • Related