phparraystext-parsing

Parse a delimited string containing key-value pairs resembling PHP's array-syntax into an associative array


I want to create an array from this string, stored in database:

$string = '"2148" => "50","2050" => "2","2403" => "1"';
$id_values = explode('=> "', $string);
foreach($id_values as $id => $value)
{
    $value_to_print .= '<img src="images/item_values/'.$id.'.gif"> - '.$value.'';
}

echo $value_to_print;

Manually defining the array works as expected:

$id_values = array("2148" => "50","2050" => "2","2403" => "1");

Solution

  • $id isn't going to be the number from the original string - it will create a new one.

    You could try this:

    $string = '"2148" => "50","2050" => "2","2403" => "1"';
    $id_values = array();
    $bits = explode(",", $string);
    foreach ($bits as $b) {
        $bobs = explode(" => ", $b);
        $id_values[$bobs[0]] = $bobs[1];
    }
    foreach($id_values as $id => $value){
        $value_to_print .= '<img src="images/item_values/'.$id.'.gif"> - '.$value.'';
    }
    

    That's untested but it should be fine.

    In the future, use json_encode and json_decode to store and retrieve arrays.

    Note: You probably want to get rid of the quotes too - just add

    $b = str_replace('"', '', $b);

    on the line before $bobs = explode(" => ", $b);