Home  >  Article  >  Backend Development  >  Handle JSON arrays and objects in PHP

Handle JSON arrays and objects in PHP

藏色散人
藏色散人forward
2019-08-10 13:59:353143browse

Handling JSON Arrays and Objects in PHP

A common cause of confusion with clients revolves around JSON arrays and objects, and how to specify them in PHP. In particular, problems are caused by empty objects and array objects. This page will show you some common patterns used in the Elasticsearch JSON API and how to convert them into PHP representations.

Empty Objects

The Elasticsearch API uses empty JSON objects in several places, which can cause problems for PHP. Unlike other languages, PHP does not have a "short" representation of an empty object. Therefore many developers don't know how to specify empty objects.

Consider adding highlighting to the query:

{
    "query" : {
        "match" : {
            "content" : "quick brown fox"
        }
    },
    "highlight" : {
        "fields" : {
            "content" : {} (1)
        }
    }
}

1. This empty JSON object is causing the problem.

The problem is that PHP will automatically convert "content" : {} to "content" : [], which will no longer be a valid Elasticsearch DSL. We need to tell PHP that the empty object is a display object, not an array. To define this query in PHP, you would:

$params['body'] = array(
    'query' => array(
        'match' => array(
            'content' => 'quick brown fox'
        )
    ),
    'highlight' => array(
        'fields' => array(
            'content' => new \stdClass() (1)
        )
    )
);
$results = $client->search($params);

We use the generic PHP stdClass object to represent an empty object and the JSON will be decoded correctly.

By using an explicit stdClass object, we can force the json_encode parser to correctly output empty objects instead of empty arrays. Unfortunately, this lengthy solution is the only way to achieve your goal in PHP... There is no "short" version of the empty object.

Array of objects

Another common pattern in the Elasticsearch DSL is array of objects. For example, consider adding a sort to a query:

{
    "query" : {
        "match" : { "content" : "quick brown fox" }
    },
    "sort" : [  (1)
        {"time" : {"order" : "desc"}},
        {"popularity" : {"order" : "desc"}}
    ]
}

1. "sort" contains a set of JSON objects

This arrangement is common, but PHP's structure can be complex. Because he needs nested arrays. The verbosity of PHP tends to obscure what's actually going on. To construct an object array, you actually need an array of arrays:

$params['body'] = array(
    'query' => array(
        'match' => array(
            'content' => 'quick brown fox'
        )
    ),
    'sort' => array(    (1)
        array('time' => array('order' => 'desc')),  (2)
        array('popularity' => array('order' => 'desc')) (3)
    )
);
$results = $client->search($params);

1. The array encodes the "sort" : [] array

2. The array encodes the {"time" : {"order" : "desc"}} objects are encoded

3. This array encodes {"popularity" : {"order" : "desc"}} objects

If you Using version 5.4 and above, I strongly recommend that you use short array syntax. It makes these nested arrays easier to read:

$params['body'] = [
    'query' => [
        'match' => [
            'content' => 'quick brown fox'
        ]
    ],
    'sort' => [
        ['time' => ['order' => 'desc']],
        ['popularity' => ['order' => 'desc']]
    ]
];
$results = $client->search($params);

Empty Object Array

Sometimes, you will encounter the DSL for the previous two patterns. This query for the score function is a good example, sometimes he needs an empty array of objects, some of which may be empty JSON objects.

For example this query:

{
   "query":{
      "function_score":{
         "functions":[
            {
               "random_score":{}
            }
         ],
         "boost_mode":"replace"
      }
   }
}

We can build it using the following PHP code:

$params['body'] = array(
    'query' => array(
        'function_score' => array(
            'functions' => array(  (1)
                array(  (2)
                    'random_score' => new \stdClass() (3)
                )
            )
        )
    )
);
$results = $client->search($params);

1. It encodes the object array: "functions" : []

2. It encodes the objects in the array: { "random_score": {} }

3.T It encodes the empty JSON object: "random_score": {}

Recommended: [PHP Tutorial]

The above is the detailed content of Handle JSON arrays and objects in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete