skip to Main Content

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?

2

Answers


  1. 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>';
    
    Login or Signup to reply.
  2. Or you could use a simple regex:

    $matches = [];
    preg_match_all('/sku=([0-9]+),color=([^|]*)/', $data, $matches);
    
    $output = [];
    foreach ($matches[1] as $k => $code) {
        $output[] = [
            'sku' => 'color',
            $code => $matches[2][$k],
        ];
    }
    

    (Assumes your SKU codes are all numeric, and that your color values don’t contain the ‘|’ character but could contain a comma)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search