Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I convert a string containing data in a specific format into an array of associative arrays in PHP?

I have a string with the following format:

$data = "sku=32300905,color=Dark Brown|sku=32300899,color=Blue|sku=32300900,color=Grey|sku=32300914,color=light Brown";

And I want to transform this string into an array of associative arrays as shown below:

Array
(
    [0] => Array
        (
            [sku] => 32300905
            [color] => Dark Brown
        )

    [1] => Array
        (
            [sku] => 32300899
            [color] => Blue
        )

    [2] => Array
        (
            [sku] => 32300900
            [color] => 
        )

    [3] => Array
        (
            [sku] => 32300914
            [color] => light Brown
        )

    [4] => Array
        (
            [sku] => 12345678
            [color] => 
        )

)

What would be the most efficient way to achieve this conversion in PHP?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can try this way to get you response

$data = "sku=32300905,color=Dark Brown|sku=32300899,color=Blue|sku=32300900,color=Grey|sku=32300914,color=light Brown";

$convertToArray = explode('|', $data);
$result = array_map(function ($pair) {

    list($key, $value) = explode(',', $pair);
    return array_combine(explode('=', $key), explode('=', $value));

}, $convertToArray);

echo '<pre>';
print_r($result);
echo '</pre>';

Or you can also do like this

$convertToArray = explode('|', $data);
        
        $result = array_map(function ($item) {
            $sku = null;
            $color = null;
        
            $newArray = explode(',', $item);
            // print_r($newArray);
            
            foreach ($newArray as $field) {
                $parts = explode('=', $field);
                if ($parts[0] === 'sku') {
                    $sku = $parts[1];
                } elseif ($parts[0] === 'color') {
                    $color = $parts[1];
                }
            }
        
            return ['sku' => $sku, 'color' => $color];
        }, $convertToArray);
        
                

                echo '<pre>';
                print_r($result);
                echo '</pre>';
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading