0

I am unable to have the array_search() working.

I have a string from an API call in a variable $myresp

[{"name":"product 1","order_id":1,"product_type":"new","qty_ordered":1,"sku":"8057","scaffale":"B-21-B"},{"name":"Product 2","order_id":1,"product_type":"old","qty_ordered":1,"sku":"8057","scaffale":"B-21-B"}]

I then use $mydata = json_decode($myresp); to get an array format

Using print_r($mydata); returns me

Array ( [0] => stdClass Object ( [name] => Product 1 [order_id] => 1 [product_type] => new [qty_ordered] => 1 [sku] => 8057 [scaffale] => B-21-B ) [1] => stdClass Object ( [name] => Product 2 [order_id] => 1 [product_type] => old [qty_ordered] => 1 [sku] => 8057 [scaffale] => B-21-B ) )

If I try using echo array_search("new", $mydata); I am expecting to get the value of the key of the array tha contains value = new (in this case array 0) .

Unfortunately is doing nothing.

What am I doing wrong?

1 Answer 1

1

You must use json_encode with the second parameter set true, so that it returns an associative array otherwise it will return an array of objects. In your case it will return a multidimensional array.

$mydata = json_decode($myresp, true); //mydata is a multidimensional array

To find the value in $mydata, you can use

$key = array_search('new', array_column($mydata, 'product_type'));
1
  • 1
    Thank you, it worked perfectly !! Commented Oct 7, 2021 at 12:32

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.