skip to Main Content

I have serialized array. It is serialized into string looking like:
*field1_name*|*field1_value*;*field2_name*|*field2_value*;*field3_name*|*field3_value* etc.
I need to get value of field 3.

At this moment i get it by:

explode("*|*", explode("*;*", serialized_array)[3])[1]

but i’m almost sure that there is better way to do this.
Is in php function that allows to turn it into associative array?

3

Answers


  1. Chosen as BEST ANSWER

    If i understand Your idea step 1 should looks like:

    $query_string = str_replace(["*;*", "*|*"], ["&", "="], $serialized_string);
    

    All of "*", "|", ";" can be in field_value, so replace all of them isn't a good way.


  2. $serialized_string = "*field1_name*|*field1_value*;*field2_name*|*field2_value*;*field3_name*|*field3_value*";
    
    // Step 1: Convert the serialized string into a query string format
    $query_string = str_replace(["*", "|", ";"], ["&", "=", ""], $serialized_string);
    
    // Step 2: Use parse_str() to convert the query string into an associative array
    parse_str($query_string, $result);
    
    // Step 3: Access the desired field by its name (e.g., field3_name)
    $field3_value = $result['field3_name'];
    
    // Print the value of field3_name
    echo $field3_value;
    

    This approach is more flexible than using multiple explode() calls and will work for an arbitrary number of fields in your serialized string.

    Login or Signup to reply.
  3. Very-very-very basic solution:

    function unserializer ($serializedData)
    {
        $unserializedData = [];
        
        foreach (explode('*;*', trim ($serializedData, '*')) as $keyVal) {
           [$key, $val] = explode ('*|*', $keyVal);
           $unserializedData[$key] = $val;
        }
        
        return $unserializedData;
    }
    
    $ser = '*field1_name*|*field1_value*;*field2_name*|*field2_value*;*field3_name*|*field3_value*';
    var_export (unserializer ($ser));
    

    In the real world, errors may need to be handled

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