2

How can I access the "code" and "type" values in PHP once I passed the array?
BTW, I'm using the "jquery-json" plugin. Is there any way to do this without any plugins?

jQuery:

$(function(){

    function product(code, type) {

        return {
            code: code,
            type: type
        }

    }

    var products = [];

    products.push(product("333", "Product one"), product("444", "Second product"));

    var jsonProducts = $.toJSON(products); 

    $.post(
        "php/process.php",
        {products: jsonProducts},
        function(data){
            $("#result").html(data);
        }
    );


});

PHP:

<?php 

$products = json_decode($_POST["products"], true);

foreach ($products as $product){
    echo $product;
}

?>

2 Answers 2

2

Each of your array offsets is a basic object.

foreach ($products as $product)
{
    echo $product->code;
    echo $product->type;
}

I'd suggest that you re-read the examples on json_decode to get a better understanding on how PHP translates JSON to PHP types

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

5 Comments

Yeah, this is what I first tried but I get this: "Notice: Trying to get property of non-object in..."
When I do print_r I get the correct array strcuture: Array ( [code] => 333 [type] => Product one ) Array ( [code] => 444 [type] => Second product )
Yeah! That works! But why the associative array doesn't work?
Oh, I got it! I have don't use "true" in json_decode for it to work. Thanks
@elclanrs, adding true as the second argument decodes the JSON to an associative array rather than an object. As you 've found :)
0

You should be able to just do $product->code and $product->type in your foreach loop.

By the way, if you want to print an array structure to check the formatting, you can use print_r.

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.