Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
Cómo agregar valores codificados en una respuesta JSON

Estoy tratando de usar PHP para generar JSON para tomar específicamente la forma deseada. A continuación se muestra un fragmento de mi código PHP:

 if($con){ $sql="select * from people"; $result=mysqli_query($con,$sql); if($result){ header("Content-Type: JSON"); $i=0; while($row = mysqli_fetch_assoc($result)){ $response[$i]['gender']=$row['gender']; $response[$i]['first']=$row['first']; $i++; } echo json_encode($response, JSON_PRETTY_PRINT); } }

Aquí está mi respuesta JSON actual

 [ { "gender":"male", "first":"Angela" }, { "gender":"female", "first":"Krista" } ]

Y aquí está mi respuesta deseada:

 { "inputs": [ { "values": { "gender": "male", "first": "Angela" } }, { "values": { "gender": "female", "first": "Krista" } } ] }
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Casi, agregue 'valores', luego sus elementos luego agreguen $response a la matriz de elementos, también el tipo de contenido para json es aplicación/json, y debe predefinir $ respuesta como una matriz, de lo contrario, obtendrá una advertencia indefinida y un valor nulo al usar en json_encode si la consulta está vacía.

 ... header("Content-Type: application/json"); $response = []; while($row = mysqli_fetch_assoc($result)){ $response[]['values'] = [ 'gender' => $row['gender'], 'first' => $row['first'] ]; } echo json_encode(['inputs' => $response], JSON_PRETTY_PRINT); ...
about 4 years ago · Juan Pablo Isaza Report

0

De esta manera:

 if ($con) { $sql = "select * from people"; $result = mysqli_query($con,$sql); if ($result) { header("Content-Type: JSON"); $response = [ "inputs" => [] ]; while ($row = mysqli_fetch_assoc($result)){ $response["inputs"][] = [ "values" => [ 'gender' => $row['gender'], 'first' => $row['first'] ] ]; } echo json_encode($response, JSON_PRETTY_PRINT); } }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!