1

I am using a MVC model in PHP. I am getting the following string from the View layer (This is a angular.js array but I am getting it as a string):

[
    {
        "name" : "item",
        "price" : "123",
        "quantity" : 12,
        "id" : 1
    }, {
        "name" : "hhh",
        "price" : "000",
        "quantity" : 12,
        "id" : 2
    }, {
        "name" : "kk",
        "price" : "88",
        "quantity" : 12,
        "id" : 3
    }
]

How can I extract the values of name, price, quantity and id from this string and put that into insert query?

1 Answer 1

1

This is what is known as a serialized array, meaning that it is a JavaScript array in string form (JSON). You can use PHP's json_decode function to deserialize the string, from there you can use it as a normal array:

$json='[
    {
        "name" : "item",
        "price" : "123",
        "quantity" : 12,
        "id" : 1
    }, {
        "name" : "hhh",
        "price" : "000",
        "quantity" : 12,
        "id" : 2
    }, {
        "name" : "kk",
        "price" : "88",
        "quantity" : 12,
        "id" : 3
    }
]';

$array=json_decode($json);

foreach ($array as &$value) {
    var_export($value->name);
    var_export($value->price);
    var_export($value->quantity);
    var_export($value->id);
}

The above should display all the values in your array. I'm not sure what you mean by "put that into the insert query", but hopefully the above will help you get access to this data.

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.