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;
Related
In my Laravel project, I've got a job set up which runs and attempts to notify a user based on their threshold and chosen alert metrics. I'm using the php end() method to get the last item in an array and then attempting to get whatever metric the user has chosen.
However, upon dumping the data, this isn't returning the last array item, it's returning every item and I'm not sure why?
When I dump my data, I'm getting this format instead of the last item in the array:
[2021-04-13 13:30:45] production.DEBUG: array (
0 =>
(object) array(
'event_category' => 'My Category',
'event_action' => 'My Event',
'event_count' => '2190',
'period_from' => '2021-04-13 00:00:00',
'period_to' => '2021-04-13 13:30:02',
'created_at' => '2021-04-13 13:30:06',
),
1 =>
(object) array(
'event_category' => 'My Category',
'event_action' => 'My Event',
'event_count' => '5184',
'period_from' => '2021-04-12 00:00:00',
'period_to' => '2021-04-12 23:57:02',
'created_at' => '2021-04-12 23:57:07',
),
2 =>
(object) array(
'event_category' => 'My Category',
'event_action' => 'My Event',
'event_count' => '3820',
'period_from' => '2021-04-11 00:00:00',
'period_to' => '2021-04-11 23:57:02',
'created_at' => '2021-04-11 23:57:07',
),
)
I should just be seeing the last item, amongst all of my code, the following is of significant value here:
/**
* Notify if data meets threshold & alert rules
*
* #return void
*/
public function notifyAlertThreshold($alerts, $data)
{
$newestDataPart = end($data) ?? null;
// alerts for data source
foreach ($alerts as $key => $alert) {
Log::debug($newestDataPart);
$metric = !isset($newestDataPart->{$alert->metric}) ? $newestDataPart : $newestDataPart->{$alert->metric};
}
}
In context, here's some mode of the code, but the primary question here, is why is my end() method not returning the last item?
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
$filters = json_decode($this->report->discovery_filters, true);
$this->reportStatus = 'complete';
$data = [];
foreach ($filters as $findableKey => $findable) {
/*
** If there are datasets on the findable objec, then we assume
** that we can build up a chart or some data structure.
*/
if (isset($findable['datasets'])) {
$pushableDatasets = [];
foreach ($findable['datasets'] as $datasetKey => $dataset) {
// query data
if (isset($dataset['query'])) {
$chartLabel = $findable['name'] ?? 'Untitled Chart';
$this->setDynamicChartOptions($chartLabel);
$additionFromField = $dataset['query']['additionFromField'] ?? '';
$resultData = [];
if ($dataset['query']['prefersConversionCalculation'] == 'yes') {
$totals = DB::table($dataset['query']['table'])
->select($dataset['query']['columns'])
->where($dataset['query']['calculateConversionFromTotals'])
->orderBy($dataset['query']['orderBy']['field'], $dataset['query']['orderBy']['direction'])
->get()
->chunk(100);
$goal = DB::table($dataset['query']['table'])
->select($dataset['query']['columns'])
->where($dataset['query']['calculateConversionByGoal'])
->orderBy($dataset['query']['orderBy']['field'], $dataset['query']['orderBy']['direction'])
->get()
->chunk(100);
$totals = $totals->flatten();
$goal = $goal->flatten();
$totalsGrouped = $this->groupData(
$totals,
$dataset['query']['groupBy'],
$dataset['query']['groupByFormat'],
$additionFromField
);
$goalsGrouped = $this->groupData(
$goal,
$dataset['query']['groupBy'],
$dataset['query']['groupByFormat'],
$additionFromField
);
$totalsGroupedFlattened = $totalsGrouped->flatten();
$goalsGroupedFlattened = $goalsGrouped->flatten();
$resultData = $this->getStructure($findable, $datasetKey, $goalsGroupedFlattened, $totalsGroupedFlattened);
array_push($pushableDatasets, $resultData);
} else {
$res = DB::table($dataset['query']['table'])
->select($dataset['query']['columns'])
->where($dataset['query']['filterBy'])
->orderBy($dataset['query']['orderBy']['field'], $dataset['query']['orderBy']['direction'])
->get()
->chunk(100);
$res = $res->flatten();
if (isset($dataset['query']['useGrouping']) && $dataset['query']['useGrouping'] == 'yes') {
$results = $this->groupData(
$res,
$dataset['query']['groupBy'],
$dataset['query']['groupByFormat'],
$additionFromField
);
// if we're using an addition function our array is already flattened
if (!empty($additionFromField)) {
$resultData = $results;
} else {
$resultData = $results->flatten();
}
array_push($pushableDatasets, $this->getStructure($findable, $datasetKey, $resultData));
}
}
$dataForAlerts = $resultData;
if ($dataset['query']['prefersConversionCalculation'] == 'yes') {
$dataForAlerts = $dataForAlerts['data'];
}
// alerting
$alerts = $this->getAlertThresholds($dataset['query']['table']);
$this->notifyAlertThreshold($alerts, $dataForAlerts);
}
}
$findable['datasets'] = $pushableDatasets;
}
array_push($data, $findable);
}
// no data or it's empty
if (!isset($data) || empty($data)) {
$this->reportStatus = 'error';
}
// create our report data entry
$this->updateReportData(false, $data);
}
I make a parser of items from DotA 2 user inventory in the Steam service. Every time I try to parse user data, I get an empty value:
{"success":true,"items":[]}, but there are items in my Steam inventory.
My function to parse items:
public function loadMyInventory() {
if(Auth::guest()) return ['success' => false];
$prices = json_decode(Storage::get('prices.txt'), true);
$response = json_decode(file_get_contents('https://steamcommunity.com/inventory/'.$this->user->steamid64.'/570/2?l=russian&count=5000'), true);
if(time() < (Session::get('InvUPD') + 5)) {
return [
'success' => false,
'msg' => 'Error, repeat in '.(Session::get('InvUPD') - time() + 5).' сек.',
'status' => 'error'
];
}
//return $response;
$inventory = [];
foreach($response['assets'] as $item) {
$find = 0;
foreach($response['descriptions'] as $descriptions) {
if($find == 0) {
if(($descriptions['classid'] == $item['classid']) && ($descriptions['instanceid'] == $item['instanceid'])) {
$find++;
# If we find the price of an item, then move on.
if(isset($prices[$descriptions['market_hash_name']])) {
# Search data
$price = $prices[$descriptions['market_hash_name']]*$this->config->curs;
$class = false;
$text = false;
if($price <= $this->config->min_dep_sum) {
$price = 0;
$text = 'Cheap';
$class = 'minPrice';
}
if(($descriptions['tradable'] == 0) || ($descriptions['marketable'] == 0)) {
$price = 0;
$class = 'minPrice';
$text = 'Not tradable';
}
# Adding to Array
$inventory[] = [
'name' => $descriptions['market_name'],
'price' => floor($price),
'color' => $this->getRarity($descriptions['tags']),
'tradable' => $descriptions['tradable'],
'class' => $class,
'text' => $text,
'classid' => $item['classid'],
'assetid' => $item['assetid'],
'instanceid' => $item['instanceid']
];
}
}
}
}
}
Session::put('InvUPD', (time() + 5));
return [
'success' => true,
'items' => $inventory
];
}
But should return approximately the following value:
{"success":true,"items":[{"classid":"2274725521","instanceid":"57949762","assetid":"18235196074","market_hash_name":"Full-Bore Bonanza","price":26}]}
Where my mistake?
First of all, you are iterating on descriptions for every assets, which is assets*descriptions iteration, it's quite a lot, but you can optimize this.
let's loop once for descriptions and assign classid and instanceid as object key.
$assets = $response["assets"];
$descriptions = $response["descriptions"];
$newDescriptions=[];
foreach($descriptions as $d){
$newDescriptions[$d["classid"]][$d["instanceid"]] = $d;
}
this will give as the ability to not loop over description each time, we can access the description of certain asset directly $newDescriptions[$classid][$instanceid]]
foreach($assets as $a){
if(isset($newDescriptions[$a["classid"]]) && isset($newDescriptions[$a["classid"]][$a["instanceid"]])){
$assetDescription = $newDescriptions[$a["classid"]][$a["instanceid"]];
$inventory = [];
if(isset($prices[$assetDescription["market_hash_name"]])){
$price = $prices[$assetDescription['market_hash_name']]["price"]*$this->config->curs;
$class = false;
$text = false;
if($price <= $this->config->min_dep_sum) {
$price = 0;
$text = 'Cheap';
$class = 'minPrice';
}
if(($assetDescription['tradable'] == 0) || ($assetDescription['marketable'] == 0)) {
$price = 0;
$class = 'minPrice';
$text = 'Not tradable';
}
$inventory["priceFound"][] = [
'name' => $assetDescription['market_name'],
'price' => floor($price),
'color' => $this->getRarity($assetDescription['tags']),
'tradable' => $assetDescription['tradable'],
'class' => $class,
'text' => $text,
'classid' => $a['classid'],
'assetid' => $a['assetid'],
'instanceid' => $a['instanceid']
];
}else{
$inventory["priceNotFound"][] = $assetDescription["market_hash_name"];
}
}
}
About your mistake:
are you Sure your "prices.txt" contains market_hash_name?
I don't see any other issue yet, operationg on the data you have provided in comment, I got print of variable $assetDescription. Please doublecheck variable $prices.
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);
}
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
I am new to WordPress. I am trying to create a WordPress table using WP_List_Table class. I created a table but it takes a long time. So, I want to create a function that allows me to create a WordPress table, where I can pass data and column array to the function and that function will, then, create the required WordPress table. I want to create table with edit, delete and sort-able functionality.
hey try this code it dynamic function but you need to pass first argument kay and name is id.
this is my class that is dynamic create the WP_List_table.
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of wplist_table
*
* #author renishkhunt
*/
if (!class_exists('WP_List_Table')) {
require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
}
class wplist_table extends WP_List_Table
{
//put your code here
var $data = array();
var $default_columns = array();
public function wplist_table($datad, $columns)
{
parent::__construct();
$this->data = $datad;
$this->default_columns = $columns;
}
function get_columns()
{
return $this->default_columns;
}
function prepare_items()
{
$columns = $this->get_columns();
$hidden = array();
$sortable = $this->get_sortable_columns();
$this->_column_headers = array($columns, $hidden, $sortable);
usort($this->data, array(&$this, 'usort_recorder'));
$per_page = 10;
$current_page = $this->get_pagenum();
$total_items = count($this->data);
// only ncessary because we have sample data
$this->found_data = array_slice($this->data, (($current_page - 1) * $per_page), $per_page);
$this->set_pagination_args(array(
'total_items' => $total_items, //WE have to calculate the total number of items
'per_page' => $per_page //WE have to determine how many items to show on a page
));
$this->items = $this->found_data;
}
function column_default($item, $column_name)
{
foreach ($this->default_columns as $keys => $values) {
if ($values == $column_name) {
if(isset($item[$column_name])){
return $item[$column_name];
}
}
}
}
function get_sortable_columns()
{
$i=0;
$sortables = array();
foreach ($this->default_columns as $keys => $values) {
if($i == 0){
$i++;
//continue;
}
$sortables[$keys] = array($values,false);
}
return $sortables;
}
function usort_recorder($a, $b)
{
$orderby = (!empty($_GET['orderby'])) ? $_GET['orderby'] : 'id';
$order = (!empty($_GET['order'])) ? $_GET['order'] : 'asc';
$resutl = strcmp($a[$orderby], $b[$orderby]);
return ( $order === 'asc') ? $resutl : -$resutl;
}
function column_Name($item)
{
$action = array(
'edit' => sprintf('Edit', $_REQUEST['page'], 'edit', $item['id']),
'delete' => sprintf('Delete', $_REQUEST['page'], 'delete', $item['id'])
);
return sprintf('%1$s %2$s', $item['name'], $this->row_actions($action));
}
function get_bulk_action()
{
$actions = array(
'delete' => 'Delete '
);
return $actions;
}
function column_db($item)
{
return sprintf("<input type='checkbox' name='id[]' value='%s'", $item['id']);
}
}
?>
just you copy that code in file and pass arguments like column name and data like this.
$data = array(
array("id" => 1, "name" => "Renish Khunt", "add" => "asd"),
array("id" => 2, "name" => "Renish Khunt", "add" => "asd"),
array("id" => 3, "name" => "Renish Khunt", "add" => "asd")
);
$columns = array(
"name" => "name",
"add" => "add"
);
then after create the class object and pass the two arguments the data and column name like this.
$mylist_table = new wplist_table($data, $columns);
echo '<div class="wrap"><h2>Custome Fields<a class="add-new-h2" href="?page=' . $_REQUEST['page'] . '&action=add">Add New</a></h2>';
$mylist_table->prepare_items();
$mylist_table->display();
echo "</div>";
i hope this is used full for you that is the dynamic class you need to display more column in $column array add column name and $data array add that name of column as key or value like this.
$data = array(
array("id" => 1, "name" => "Renish Khunt", "add" => "asd","newcolumn"=>"value"),
array("id" => 2, "name" => "Renish Khunt", "add" => "asd","newcolumn"=>"value"),
array("id" => 3, "name" => "Renish Khunt", "add" => "asd","newcolumn"=>"value")
);
$columns = array(
"name" => "name",
"add" => "add",
"newcolumn"=>"New Column"
);
like this i hope this code is used full for you.
thank you.