Search code examples
phparraystext-parsingdelimited

Parse a text file into an array of associative arrays by splitting on semicolons then by equals signs


I have created this array from a text file by exploading every line by ';'.

How can I set the value before the '=' sign as key and the other one after the '=' sign as value?

Array
(
    [0] => Array
        (
            [0] => title=PHILIPS MIXER H31453
            [1] => gramaj=buc
            [2] => greutate=1
            [3] => prettotal=116.07
            [4] => pretredus=0
            [5] => poza=110.jpg
        )
    [0] => Array
        (
            [0] => titlu=PHILIPS MIXER H31453
            [1] => gramaj=buc
            [2] => greutate=1
            [3] => prettotal=116.07
            [4] => pretredus=0
            [5] => poza=110.jpg
        )
)

The result should be like:

[titlu] => PHILIPS MIXER H31453
[gramaj] => buc
[greutate] => 1
[prettotal] => 116.07
// and so on...

This is where I need it.

function runSql(){
    session_start();
    header('Content-type: text/html;charset=utf8');
    global $outcount;

    $db = $this->pdoconnect();
    $db->setErrorLog(true);

    $files = $_SESSION['sql'];
    $to_process = array_shift($files);
    $get_sql = @file_get_contents($to_process);
    @unlink($to_process);

    $split = explode(";", $get_sql);
    unset($split[count($split) - 1]); // Clear the last empty element

    $final_array = array();
    foreach ($split as $row) {
        $final_array[] = explode(',', $row); // Explode each row by , to each row of final_array
    }
            
    //$stmt = $db->insertBatch('produse', $final_array, true)->getAllLastInsertId();
            
    echo 1;
}

Solution

  • Just do the same thing, explode each item and use the first part as the key and second part as the value

    $split       = explode(";", $get_sql);
    $final_array = array();
    
    foreach ($split as $row) {
        $arr = explode(',', $row);
        $res = array();
    
        foreach($arr as $item) {
            $parts = explode("=", $item);
            $res[$parts[0]] = $parts[1];
        }
    
        $final_array[] = $res;
    }