使用PHP正则表达式计算ElasticSearch的结果

I would like to save my count result when ElasticSearch return this line:

{"took":13,"timed_out":false,"_shards":{"total":5,"successful":5,"failed":0},"hits":{"total":2242,"max_score":1.0,"hits":[{"_index":"

I wish to save the total result into a variable, but I don't found the good regex rule to save "2242".

Why do you think you need a regex? Just use json_decode and access it like this; closed your JSON for this example:

$raw_json = '{"took":13,"timed_out":false,"_shards":{"total":5,"successful":5,"failed":0},"hits":{"total":2242,"max_score":1.0,"hits":[{"_index":"999999"}]}}';

$decoded_json = json_decode($raw_json);

echo '<pre>';
print_r($decoded_json);
echo '</pre>';

The output would be this:

stdClass Object
(
    [took] => 13
    [timed_out] => 
    [_shards] => stdClass Object
        (
            [total] => 5
            [successful] => 5
            [failed] => 0
        )

    [hits] => stdClass Object
        (
            [total] => 2242
            [max_score] => 1
            [hits] => Array
                (
                    [0] => stdClass Object
                        (
                            [_index] => 999999
                        )

                )

        )

)

Then knowing that you just access the total under hits like this:

$hits_total = $decoded_json->hits->total;

echo $hits_total;

Or if objects are not easy for you to parse, just set json_decode to return an array by setting the second parameter to true.

$decoded_json = json_decode($raw_json, true);

And then access it like this:

$hits_total = $decoded_json['hits']['total'];

echo $hits_total;

You could use the count API facility in ElasticSearch to reduce data size for parsing. But anyway you should use json_decode to parse returned results.