1

I am trying to get attribute option Ids for a sku using this below api call.

http://localhost/rest/V1/configurable-products/sh8/options/all

I used this curl request:

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "http://localhost/rest/V1/configurable-products/sh8/options/all",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => array(
    "cache-control: no-cache",
    "postman-token: f1457b50-7a5e-4f08-d6ee-8e3b0aad21bd"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {

   echo $response;
    }

I got this below response:

[
    {
        "id": 26,
        "attribute_id": "145",
        "label": "size",
        "position": 1,
        "values": [
            {
                "value_index": 25
            },
            {
                "value_index": 27
            },
            {
                "value_index": 28
            },
            {
                "value_index": 29
            }
        ],
        "product_id": 161
    },
    {
        "id": 27,
        "attribute_id": "146",
        "label": "color",
        "position": 0,
        "values": [
            {
                "value_index": 30
            },
            {
                "value_index": 31
            },
            {
                "value_index": 32
            }
        ],
        "product_id": 161
    }
]

But when I try to access this in foreach like

 foreach ($response as  $value) {
       var_dump($value);
    }

I get this below error:

Exception #0 (Exception): Warning: Invalid argument supplied for foreach()
1

It gives the error because response is in json you need to do

$response = json_decode($response);

before passing to foreach

I hope this will help

  • @Ramesh brother please mark my answer correct if it's resolve your issue. this question is still open for others it may also help others as well. – Muhammad Hasham Mar 12 at 11:39
0

Your $response result is in JSON format so you have to decode it in order to access data.

$data = json_decode($response); 

And in your foreach do like this to get the value of the key attribute_id:

foreach ($data as $value){
    echo "<br/>";
    echo $value['attribute_id'];
}  

Note: you can change the key to what you need to get

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.