简体   繁体   中英

How to filter json encode array count?

In my example I have a PHP script that, from AJAX, does a tally of everyone named 'Richard.' I would like to further modify this by counting the people named Richard, that match the age of some input value, as shown in $theirage .

Specifically, I would like to sum up the two ages, and only show the ones that equal 20 in my array. $row[age] corresponds to the value age in my DB, while $theirage is a user input.

At the end I want to only tally the summed ages that equal to 20, in this case.

    $theirage = $_GET['theirage'];
    $query = mysqli_query($con, "SELECT count(*) as cnt FROM members WHERE
    name = 'Richard'
    ");
    $row = mysqli_fetch_assoc($query);
    $bow = $row['age'] + $theirage;
    $if ($bow = 20){
    $person = $row['cnt'];} 

echo json_encode( array(
    'person' => $person
) );    

How might I go about this?

I suggest you query members table to count all who are matching your criteria: specific name 'Richard' and specific age $_GET['theirage'] :

<?php
$theirAge = $_GET['theirage'];

// This is important: since we're using $theirAge in query string, we need to escape it
$theirAge = mysqli_escape_string($theirAge);

// Let's query all members whose name is Richard and age is equal to $_GET['theirage']
$query = mysqli_query($con, "SELECT count(*) FROM members WHERE name = 'Richard' AND age + $theirAge = 20");

$row = $query->fetch_row();

$totalRichardsOfGivenAge = $row[0]; // here is your result.

// And now let's return JSON
echo json_encode($totalRichardsOfGivenAge)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM