-1

I'm trying to call a REST endpoint that is expecting an object with an array 'campaigns' and a boolean 'getChildren'. The issue is that the array is sometimes serialized as an object instead of an array.

The incorrect request I'm getting :

   {
    "campaigns":
      {
        "1":"1006352",
        "2":"1006347",
        "3":"1006350",
        "4":"1006349",
        "5":"1006348",
        "6":"1006345",
        "7":"1006344",
        "8":"1006343"
       },
    "getChildren":false
   }

What I want (and that I get sometimes) :

 {
  "campaigns":["1006351","1006346"],
  "getChildren":false
 }

Here is my code :


            $campaignIds = array_map(function ($item) use ($networkIds) {
            return $item->nid;
        },
            array_filter($items, function ($item) use ($networkIds) {
                return empty((int)$item->nb_shared);
            }));

        $consoWithoutChildren = EndpointClient::getConsumptionByCampaign($networkIds, $campaignIds);

I want the 'campaigns' parameter to be always interpreted as an array.

I tried json_encode() but it escapes the array, causing issues in the use cases where I had valid JSON, like that :

{"campaigns":"[\"1006351\",\"1006346\"]","getChildren":false}

Any idea what is wrong ?

1
  • You need to extract and provide a minimal reproducible example. In particular it's unclear how you come to the conclusion that json_encode() escapes an array in any way. Also, nobody here knows what happens in the other parts of your program or what e.g. $networkIds is. Commented Feb 10, 2020 at 10:23

1 Answer 1

0

array_filter keeps the index of the array elements. So if the first element of your array does not fulfill the condition of your array_filter, you have no element at the 0 index. To be serialized properly, the array must not have null values in it.

The solution is to reassign the array elements to 0 to n index, with array_values().

Like this :

        // array_values is needed to have arrays' indices beginning at 0.
        // If not, the JSON parsing would consider the array an object.
        // Like {"campaigns":{"1":"1006352","2":"1006347"}}
        $campaignIds = array_values(
            array_map(
                function ($item) use ($networkIds) {
                    return $item->nid;
                },
                array_filter(
                    $items,
                    function ($item) use ($networkIds) {
                        return empty((int)$item->nb_shared);
                    }
                )
            )
        );

        $consoWithoutChildren = EndpointClient::getConsumptionByCampaign($networkIds, $campaignIds);

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

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.