I have written following code:
try {
$json = array('success' => true);
$read = $this->read;
$readresult = $read->fetchAll("SELECT * FROM brand");
foreach($readresult as $r) {
$json['brands'][] = array(
'id' => $r['brand_id'],
'name' => $r['name'],
'description' => $r['description'],
);
}
return $json;
} catch (Exception $e) {
$message = $e->getMessage();
echo json_encode(array("status" => "500", "error" => $message));
}
In this code I am trying to display all the brand records from the database table.
But the problem is when I am trying to output the result the it is only displaying one record.
Can anyone please check what is the problem.
The output of the code above is:
{
"success":true,
"products":[
{
"id":"4",
"name":"Test",
"href":"http:\/\/localhost:81\/magento\/index.php\/catalog\/product\/view\/id\/4\/",
"thumb":"http:\/\/localhost:81\/magento\/media\/catalog\/product\/cache\/0\/thumbnail\/9df78eab33525d08d6e5fb8d27136e95\/images\/catalog\/product\/placeholder\/thumbnail.jpg",
"pirce":"$111,111.00"
}
]}
try like this,
$json['brands'] = array();
foreach($readresult as $r) {
$brand = array(
'id' => $r['brand_id'],
'name' => $r['name'],
'description' => $r['description'],
);
array_push($json['brands'],$brand);
}
Related
I'm working on my REST API responses with PHP.
Here is my backend that generates the responses:
$query = $this->db->query("SELECT some_params from some_table ");
$result = $query->result();
foreach($result as $row){
$obj[] = array(
'title' => $row['title'],
'price' => $row['price'],
);
}
print_r(json_encode($obj));
and with that I have the following response: an array of json objects
[
{
"title":"Marketing",
"price":"0"
},
{
"title":"SAP B1",
"price":"10"
}
]
What I would like to do is return a new object, something like this:
{
"apiVersion": "2.0",
"data": {
{
"title":"Marketing",
"price":"0"
},
{
"title":"SAP B1",
"price":"10"
}
}
}
Does anyone have any idea how I could implement this? thanks!
You can easily have a class or function to do that for you. Some thing like below should help,
// provided you are using php > 7 . otherwise parmas
// can become $data, $apiversion ( without typecasting )
function api_reponse(array $data, string $apiVersion)
{
return json_encode([
'apiVersion' => $apiVersion,
'data' => $data
])
}
You can then use,
$query = $this->db->query("SELECT some_params from some_table ");
$result = $query->result();
foreach($result as $row){
$obj[] = array(
'title' => $row['title'],
'price' => $row['price'],
);
}
print_r( api_response($obj, '2.0') );
i want to return data from a web services with php in one group json container. my below script gives me each of the data seperated like this
{"No":"01","Name":"JOSEPH"}{"No":"02","Name":"AMINU"}
But i wan it to return like this
[{"No":"01","Name":"JOSEPH","No":"02","Name":"AMINU"}]
below is my script
try{
$service = new NTLMSoapClient($pageURL);
$params = array('filter' => array(
array('Field' => 'District_Name', 'Criteria' => '')
),
'setSize' => 2); //setSize =0 will return all rows - Can cause performance issue with large results set!
$result = $service->ReadMultiple($params);
$resultSet = $result->ReadMultiple_Result->customer;
if (is_array($resultSet)) {
foreach($resultSet as $item) {
$data=array('No' => $item->No,'Name' => $item->Name);
echo json_encode($data);
}
}
else {
echo json_encode('record not found');
}
}
catch (Exception $e) {
echo "<hr><b>ERROR: SoapException:</b> [".$e."]<hr>";
echo "<pre>".htmlentities(print_r($service->__getLastRequest(),1))."</pre>";
}
Try you foreach with this.
try{
$service = new NTLMSoapClient($pageURL);
$params = array('filter' => array(
array('Field' => 'District_Name', 'Criteria' => '')
),
'setSize' => 2); //setSize =0 will return all rows - Can cause performance issue with large results set!
$result = $service->ReadMultiple($params);
$resultSet = $result->ReadMultiple_Result->customer;
if (is_array($resultSet)) {
$jsonArray = [];
foreach($resultSet as $item) {
$data = array('No' => $item->No,'Name' => $item->Name);
$jsonArray = array_merge($jsonArray, $data);
}
echo json_encode($jsonArray);
}
else {
echo json_encode('record not found');
}
}
catch (Exception $e) {
echo "<hr><b>ERROR: SoapException:</b> [".$e."]<hr>";
echo "<pre>".htmlentities(print_r($service->__getLastRequest(),1))."</pre>";
}
try{
$service = new NTLMSoapClient($pageURL);
$params = array('filter' => array(
array('Field' => 'District_Name', 'Criteria' => '')
),
'setSize' => 2); //setSize =0 will return all rows - Can cause performance issue with large results set!
$result = $service->ReadMultiple($params);
$resultSet = $result->ReadMultiple_Result->customer;
if (is_array($resultSet)) {
$data = array();
foreach($resultSet as $item) {
$data = $data + array('No' => $item->No,'Name' => $item->Name);
}
echo json_encode($data);
}
else {
echo json_encode('record not found');
}
}
catch (Exception $e) {
echo "<hr><b>ERROR: SoapException:</b> [".$e."]<hr>";
echo "<pre>".htmlentities(print_r($service->__getLastRequest(),1))."</pre>";
}
I'm running into some issues getting the correct JSON output from my SQL query. Essentially what I'm struggling with is getting an array of options objects as opposed to singular option objects.
$query = 'SELECT matchup.matchupID, matchup_option.player_name, matchup_option.player_id FROM matchup
INNER JOIN matchup_option
ON matchup_option.matchupID= matchup.matchupID;';
$attachments = $db->query($query);
$data = array();
while ($attachment = $db->fetch_array($attachments)){
$data[] = array (
'id' => $attachment['matchupID'],
'options' => array(
array (
"name" => $attachment['player_name'],
"playerid" => $attachment['player_id']
)
)
);
//VAR_DUMP($attachment);
}
$data = array("matchup"=>$data);
print json_encode($data);
Gives me this output:
{
"matchup":[
{
"id":"111222",
"options":[
{
"name":"111",
"playerid":"111"
}
]
},
{
"id":"111222",
"options":[
{
"name":"222",
"playerid":"222"
}
]
}
]
}
And here's what I'm trying to get to:
{
"matchup":[
{
"id":"111222",
"options":[
{
"name":"111",
"playerid":"111"
},
{
"name":"222",
"playerid":"222"
}
]
}
]
}
I'd like to follow best practices as well as structure this appropriately, if there's a better way to go about this, please let me know!
You need to store $attachment['matchupID'] as an array key of $data:
$data = array();
while ($attachment = $db->fetch_array($attachments)){
if (!isset($data[$attachment['matchupID']])) {
$data[$attachment['matchupID']] = array (
'id' => $attachment['matchupID'],
'options' => array()
);
}
$data[$attachment['matchupID']]['options'][] = array (
"name" => $attachment['player_name'],
"playerid" => $attachment['player_id']
);
}
// use `array_values` to reindex `$data`
$data = array("matchup" => array_values($data));
print json_encode($data);
I'm getting Informations from the Zabbix Api with a PHP library. At the moment I get the "lastvalue" from the json Array:
try {
// connect to Zabbix-API
$api = new ZabbixApi($api_url, $username, $password);
$params = array(
'groupids' => '2',
'real_items' =>TRUE,
'monitored_items' =>TRUE,
'search' => array('name' => 'Disk root used p'),
'selectFunctions' => 'extend',
'output' => 'extend',
'sortfield' => 'name',
'limit' => '1'
);
$trends = $api->itemGet($params); // get data from api
$names = array();
foreach($trends as $trend) { // loop through the returned data
$names[] = $trend->lastvalue;
}
//print_r($names);
} catch(Exception $e) {
// Exception in ZabbixApi catched
echo $e->getMessage();
}
But now I want to get the "lastvalue" plus the "name" of the Item in this Array for example like that: "name"+"lastvalue". How can I get both of them into my array $names[]?
Here is my answer from my comments, hope its what you are looking for!
$trends = $api->itemGet($params);
$names = array();
foreach($trends as $trendKey => $trendValue)
{
$names[$trendKey] = $trendValue;
}
#Test the names array
foreach ($names as $nameKey => $nameValue)
{
print("{$nameKey} = {$nameValue}<br />");
}
Return value:
groupids = 2
real_items = TRUE
...
sortfield = name
limit = 1
okay I am trying to learn here I am a noob, basically, this is my current (server.php) code,
<?php
/**
* Sample php server script for a wookmark integration
*
* #author Sebastian Helzle <sebastian#helzle.net>
*/
/**
* Basic class which provides all functions to retrieve and paginate pictures
*/
class PictureDatabase {
/**
* #var array $data
*/
protected $data;
/**
* #var int $itemsPerPage
*/
protected $itemsPerPage;
function __construct($data, $itemsPerPage) {
$this->data = $data;
$this->itemsPerPage = $itemsPerPage;
}
/**
* Returns the pictures of the given page or an empty array if page doesn't exist
* #param int $page
* #return array
*/
public function getPage($page=1) {
if ($page > 0 && $page <= $this->getNumberOfPages()) {
$startOffset = ($page - 1) * $this->itemsPerPage;
return array_slice($this->data, $startOffset, $this->itemsPerPage);
}
return array();
}
/**
* Returns the maximum number of pages
* #return int
*/
public function getNumberOfPages() {
return ceil(count($this->data) / $this->itemsPerPage);
}
}
// Our data source
$data = include ('xyz.php');
// Make data array a bit bigger to have more pages
for ($i=0; $i<3; $i++) {
$data = array_merge($data, $data);
}
// Create instance of picture database with 10 items per page and our data as source
$pictureDatabase = new PictureDatabase($data, 10);
$result = array(
'success' => TRUE,
'message' => 'Retrieved pictures',
'data' => array()
);
$callback = isset($_REQUEST['callback']) ? $_REQUEST['callback'] : false;
// Get requested page number from request and return error message if parameter is not a number
$page = 1;
try {
$page = intval($_REQUEST['page']);
} catch (Exception $e) {
$result['success'] = FALSE;
$result['message'] = 'Parameter page is not a number';
}
// Get data from database
$result['data'] = $pictureDatabase->getPage($page);
if (count($result['data']) == 0 || $page >= $pictureDatabase->getNumberOfPages()) {
$result['success'] = TRUE;
$result['message'] = 'No more pictures';
}
// Encode data as json or jsonp and return it
if ($callback) {
header('Content-Type: application/javascript');
echo $callback.'('.json_encode($result).')';
} else {
header('Content-Type: application/json');
echo json_encode($result);
}
okay now under //datasource, the original is
$data = array (
array (
'id' => "1",
'title' => "First image",
'url' => "http://www.example.org/1",
'width' => "200",
'height' => "283",
'image' => "/images/image_1_big.jpg",
'preview' => "/images/image_1.jpg"
),
array (
'id' => "2",
'title' => "Second image",
'url' => "http://www.example.org/2",
'width' => "200",
'height' => "300",
'image' => "/images/image_2_big.jpg",
'preview' => "/images/image_2.jpg"
)
);
now what I have done with the help of few people here is gotten another (xyz.php) file to print out this from sql,
<?php
// Our data source
$conn = mysql_connect("", "", "");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
//= Query ========================//
$sql = mysql_query("select id, title, url, width, height, image, preview from mmf_content");
//= Closed while ====================//
/*everytime it fetches the row, adds it to array...*/
$foo = "array (\n";
while ($row=mysql_fetch_assoc($sql)){
$foo.= "array (\n";
foreach ($row as $key => $value){
$foo .= "'{$key}' => \"{$value}\",\n";
}
$foo = substr($foo,0,strlen($foo)-2)."\n";//removes the comma at the end
$foo .="),\n";
}
$foo = substr($foo,0,strlen($foo)-2)."\n";//removes the comma at the end
$foo .= ');';
echo '<pre>'.$foo.'</pre>';
?>
this is the printout,
array (
array (
'id' => "1",
'title' => "First image",
'url' => "http://www.example.org/1",
'width' => "200",
'height' => "283",
'image' => "/images/image_1_big.jpg",
'preview' => "/images/image_1.jpg"
),
array (
'id' => "2",
'title' => "Second image",
'url' => "http://www.example.org/2",
'width' => "200",
'height' => "300",
'image' => "/images/image_2_big.jpg",
'preview' => "/images/image_2.jpg"
)
);
now currently if in the server.php
// Our data source
$data = include ('xyz.php');
it doesnt work, but if i manually put the printout it works perfectly.
so how do i make $data = to printout of xyz.php
If you include xyz.php you will have access to everything inside so no need to return anything. Just put this inside xyz.php:
$data = array();
while ($row=mysql_fetch_assoc($sql)){
$data[]= $row;
}
Then inside server.php you will be able to access $data.
change
$foo = "array (\n";
while ($row=mysql_fetch_assoc($sql)){
$foo.= "array (\n";
foreach ($row as $key => $value){
$foo .= "'{$key}' => \"{$value}\",\n";
}
$foo = substr($foo,0,strlen($foo)-2)."\n";//removes the comma at the end
$foo .="),\n";
}
$foo = substr($foo,0,strlen($foo)-2)."\n";//removes the comma at the end
$foo .= ');';
echo '<pre>'.$foo.'</pre>';
to
$foo = array();
while ($row=mysql_fetch_assoc($sql)){
$foo[]= $row;
}
return $foo;