0
[{"name":"se","value":"test1"},{"name":"model","value":"test2"},{"name":"filter_preference","value":"test3"},{"name":"seved","value":"test4"}]

I have json, and I would like to parse it, and to get for "segment" => "test1" and so on.

i have done this

$json2= json_encode($loadFilter);
    $json2 = json_decode($json2, true);

    foreach ($json2->$key as $value)
    {
        echo $key ."=>".$value;
    }

always getting Invalid argument supplied for foreach() !!!

I am doing it WP ajax callback.

3 Answers 3

3

Your foreach syntax is wrong to access the $key.

foreach ($json2 as $key => $value) {
    echo $key ."=>".$value;
}

Edit from your comments:

You didn't give the "real" format in your question, your array is contained in 'filter_preference', so you have to iterate over $json2['filter_preference'].

foreach ($json2['filter_preference'] as $key => $value) {
    echo $key ."=>".$value;
}
Sign up to request clarification or add additional context in comments.

8 Comments

Thx for replying, I have tried, and i get for key filterpreference which is the name of column, and the rest is the value, buthow can i get to the "segment" - "test1" ?!
@user3042036 Can you add a var_dump of the $loadFilter variable please ?
i get object(stdClass)#7188 (1) { ["filter_preference"]=> string(378) ""[{\\\"name\\\":\\\"segment\\\",\\\"value\\\":\\\"Test1\\\"},{\\\"name\\\":\\\"model\\\",\\\"value\\\":\\\"\\\"},{\\\"name\\\":\\\"filter_preference\\\",\\\"value\\\":\\\"Test2\\\"}]"" }
@user3042036 Edited my answer, should fit your input now.
thanks, for replying so fast, now i get "Invalid argument supplied for foreach()" I apologize for not giving real format.
|
1

you need to map key value for sub array. try this:

   foreach ($json2 as $key=>$value)
        {
            echo $key ."=>".$value;
        }

1 Comment

Thx for replying, I have tried, and i get for key filterpreference which is the name of column, and the rest is the value, but how can i get to the "segment" - "test1" ?!
0

One odd suggestion here:

If you want to use array for this then you can convert object to array using following code:

function objectToArray($d) {
        if (is_object($d)) {
            // Gets the properties of the given object
            // with get_object_vars function
            $d = get_object_vars($d);
        }

        if (is_array($d)) {
            /*
            * Return array converted to object
            * Using __FUNCTION__ (Magic constant)
            * for recursive call
            */
            return array_map(__FUNCTION__, $d);
        }
        else {
            // Return array
            return $d;
        }
    }

$array_new = objectToArray($json2);

http://wonderphp.wordpress.com/2014/03/20/convert-object-to-array-and-vice-versa/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.