0

I have the following json object:

{"keywords": "foo", "industries":"1,37","contractTypes":"1"}

How can i convert the following key values in to an array as follows:

{"keywords": "foo", "industries": ["1", "37"], "contractTypes": ["1"]}

So basically I want to loop through the object and if property industries and contractTypes exist and not empty then convert the values into array.

1
  • Any reason why when you convert it, value for keywords is not in an array but value for contractTypes is? Commented Jun 26, 2017 at 23:09

1 Answer 1

2
  • Define the list of properties that you want to convert to arrays

    $array_properties = ['industries', 'contractTypes'];
    
  • decode the JSON

    $object = json_decode($json);
    
  • Iterate the properties you defined and convert each one to an array if it exists on the object.

    foreach ($array_properties as $property) {
        if (isset($object->$property)) {
            $object->$property = explode(',', $object->$property);
        }
    }
    
  • You can re-encode the object to JSON afterward if you need to.

    $object = json_encode($object);
    
  • get money

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.