如何将api请求的json数据存储到数组中

时间:2016-03-01 15:56:40

标签: php json

我已经创建了一个发出API请求的函数。 (functions.php)我已将此函数调用到一个名为(results.php)的文件中,该函数从搜索输入中选择ID,从数据库中取出lat和long, 我希望能够为返回的数据执行每个操作。对于每个对象,将lat和long存储到一个数组中。将json数据粘贴到json查看器中以更好地查看它。整个事情从数据库连接到数据输出工作我只是想不出如何将这个json数据存储到变量中,就像我说把每个对象的lat和long放入一个数组

的functions.php

CREATE TRIGGER timecard_employee_name_delete_trigger DELETE ON timecard_fields
WHEN OLD.timecard_field_name='employee_name'
BEGIN
    INSERT INTO templates (template_name) VALUES('name');
END;

} }

RESULTS.PHP

function locate($id, $connect) { //connect is coming from connection.php


 // Using prepared Statements means that SQL injection is not possible. Selects      ID from search input takes lat and long.

  if ($stmt = $connect->prepare("SELECT Lat, Lng FROM List WHERE ID = ? LIMIT 1")or die(mysql_error())) { 
  $stmt->bind_param('i', $id ); // Bind "$id" to parameter.
  $stmt->execute(); // Execute the prepared query.
  $stmt->store_result();
  $stmt->bind_result($lat, $lng); // get variables from result.
  $stmt->fetch();

  if($stmt->num_rows == 1) // If the id exists
  { 
    // Point to where you downloaded the phar
    include('httpful.phar');

    // Api request!
    $response = \Httpful\Request::get('https://data.police.uk/api/crimes-street/all-crime?lat='.$lat.'&lng='.$lng)->send();
    echo $response;

  } 

  else
  {
     // No lat & long exists. 
     echo 'noUser';
     return false;
  }

JSON DATA

$id=$_POST["hiddenField"]; //ID equals the hidden field post made from the   search university form
locate($id, $connect); //function from functions.PHP

1 个答案:

答案 0 :(得分:1)

See json_decode()

//Input (json) string/array
$string = '[{"Foo":"bar","123":456}]';

//Convert to PHP array
$array = json_decode($string, true):

//Output to check
print_r($array);

以上将输出:

Array
(
    [0] => Array
        (
            [Foo] => bar
            [123] => 456
        )
)