Handle JSON arrays and objects in PHP

藏色散人
Release: 2023-04-07 07:20:02
forward
3076 people have browsed it

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)
        }
    }
}
Copy after login

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);
Copy after login

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"}}
    ]
}
Copy after login

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);
Copy after login

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);
Copy after login

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"
      }
   }
}
Copy after login

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);
Copy after login

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!

Related labels:
php
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!