I have this bit of code:
<?php
#
# Sample Socket I/O to CGMiner API
#
function getsock($addr, $port)
{
$socket = null;
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false || $socket === null)
{
$error = socket_strerror(socket_last_error());
$msg = "socket create(TCP) failed";
echo "ERR: $msg '$error'\n";
return null;
}
$res = socket_connect($socket, $addr, $port);
if ($res === false)
{
$error = socket_strerror(socket_last_error());
$msg = "socket connect($addr,$port) failed";
echo "ERR: $msg '$error'\n";
socket_close($socket);
return null;
}
return $socket;
}
#
# Slow ...
function readsockline($socket)
{
$line = '';
while (true)
{
$byte = socket_read($socket, 1);
if ($byte === false || $byte === '')
break;
if ($byte === "\0")
break;
$line .= $byte;
}
return $line;
}
#
function request($cmd)
{
$socket = getsock('127.0.0.1', 4028);
if ($socket != null)
{
socket_write($socket, $cmd, strlen($cmd));
$line = readsockline($socket);
socket_close($socket);
if (strlen($line) == 0)
{
echo "WARN: '$cmd' returned nothing\n";
return $line;
}
print "$cmd returned '$line'\n";
if (substr($line,0,1) == '{')
return json_decode($line, true);
$data = array();
$objs = explode('|', $line);
foreach ($objs as $obj)
{
if (strlen($obj) > 0)
{
$items = explode(',', $obj);
$item = $items[0];
$id = explode('=', $items[0], 2);
if (count($id) == 1 or !ctype_digit($id[1]))
$name = $id[0];
else
$name = $id[0].$id[1];
if (strlen($name) == 0)
$name = 'null';
if (isset($data[$name]))
{
$num = 1;
while (isset($data[$name.$num]))
$num++;
$name .= $num;
}
$counter = 0;
foreach ($items as $item)
{
$id = explode('=', $item, 2);
if (count($id) == 2)
$data[$name][$id[0]] = $id[1];
else
$data[$name][$counter] = $id[0];
$counter++;
}
}
}
return $data;
}
return null;
}
#
if (isset($argv) and count($argv) > 1)
$r = request($argv[1]);
else
$r = request('summary');
#
echo print_r($r, true)."\n";
#
?>
Which outputs this information:
summary returned 'STATUS=S,When=1399108671,Code=11,Msg=Summary,Description=cgminer 4.3.0hf|SUMMARY,Elapsed=531,MHS av=453052.33,MHS 5s=537024.44,MHS 1m=458922.01,MHS 5m=375184.88,MHS 15m=201623.38,Found Blocks=0,Getworks=16,Accepted=518,Rejected=12,Hardware Errors=271,Utility=58.54,Discarded=276,Stale=0,Get Failures=0,Local Work=65806,Remote Failures=0,Network Blocks=1,Total MH=240524241.0000,Work Utility=5589.33,Difficulty Accepted=49008.00000000,Difficulty Rejected=448.00000000,Difficulty Stale=0.00000000,Best Share=93465,Device Hardware%=0.5450,Device Rejected%=0.9059,Pool Rejected%=0.9059,Pool Stale%=0.0000,Last getwork=1399108671|'
Array
(
[STATUS] => Array
(
[STATUS] => S
[When] => 1399108671
[Code] => 11
[Msg] => Summary
[Description] => cgminer 4.3.0
)
[SUMMARY] => Array
(
[0] => SUMMARY
[Elapsed] => 531
[MHS av] => 453052.33
[MHS 5s] => 537024.44
[MHS 1m] => 458922.01
[MHS 5m] => 375184.88
[MHS 15m] => 201623.38
[Found Blocks] => 0
[Getworks] => 16
[Accepted] => 518
[Rejected] => 12
[Hardware Errors] => 271
[Utility] => 58.54
[Discarded] => 276
[Stale] => 0
[Get Failures] => 0
[Local Work] => 65806
[Remote Failures] => 0
[Network Blocks] => 1
[Total MH] => 240524241.0000
[Work Utility] => 5589.33
[Difficulty Accepted] => 49008.00000000
[Difficulty Rejected] => 448.00000000
[Difficulty Stale] => 0.00000000
[Best Share] => 93465
[Device Hardware%] => 0.5450
[Device Rejected%] => 0.9059
[Pool Rejected%] => 0.9059
[Pool Stale%] => 0.0000
[Last getwork] => 1399108671
)
)
How can I get a specific value? For example, how can I output only '[MHS 15m]'
if $res is the variable containing the array you can get the value as
echo $res['SUMMARY']['MHS 15m'];
Related
Please help me to extract and display the values from this array..
This is the output when I do a print_r($array); :
Array
(
[0] => SPD Object
(
[DRIVERNAME] => SPD Barry
[STARTTIME] => 07:44
[FINISHTIME] => 18:12
[STOP] =>
[SEQUENCENO] => 37
[PLACENAME] => AMSTERDAM ZUIDOOST
[ARRIVALTIME] => 17:32
)
[1] => SPD Object
(
[DRIVERNAME] => SPD Brady
[STARTTIME] => 07:36
[FINISHTIME] => 15:53
[STOP] =>
[SEQUENCENO] => 32
[PLACENAME] => NIEUWEGEIN
[ARRIVALTIME] => 15:30
)
[2] => SPD Object
(
[DRIVERNAME] => SPD Bram
[STARTTIME] => 08:11
[FINISHTIME] => 18:32
[STOP] =>
[SEQUENCENO] => 32
[PLACENAME] => LAGE ZWALUWE
[ARRIVALTIME] => 17:28
)
)
What I want to do is, get this Driver Name and Sequence Number and echo them.
UPDATE :
My full code can be found below.
I get a xml file which contain this kind of stuff :
<TRIP>
<DRIVERNAME>SPD Barry</DRIVERNAME>
<STARTTIME>07:44</STARTTIME>
<FINISHTIME>18:12</FINISHTIME>
<STOP>
<SEQUENCENO>1</SEQUENCENO>
<PLACENAME>ROTTERDAM</PLACENAME>
<ARRIVALTIME>08:30</ARRIVALTIME>
</STOP>
</TRIP>
Here is my PHP file to collect data into an array.
<?php
class SPD {
function SPD ($aa) {
foreach ($aa as $k=>$v)
$this->$k = $aa[$k];
}
}
function readDatabase($filename) {
// read the XML database of aminoacids
$data = implode("", file($filename));
$parser = xml_parser_create();
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
xml_parse_into_struct($parser, $data, $values, $tags);
xml_parser_free($parser);
// loop through the structures
foreach ($tags as $key=>$val) {
if ($key == "TRIP") {
$molranges = $val;
// each contiguous pair of array entries are the
// lower and upper range for each molecule definition
for ($i=0; $i < count($molranges); $i+=2) {
$offset = $molranges[$i] + 1;
$len = $molranges[$i + 1] - $offset;
$tdb[] = parseMol(array_slice($values, $offset, $len));
}
} else {
continue;
}
}
return $tdb;
}
function parseMol($mvalues) {
for ($i=0; $i < count($mvalues); $i++) {
$mol[$mvalues[$i]["tag"]] = $mvalues[$i]["value"];
}
return new SPD($mol);
}
$db = readDatabase("test.xml");
if(is_array($db)){
foreach($db as $item) {
echo $item->DRIVERNAME;
echo $item->SEQUENCENO;
}
}
?>
What I want to do is, echo Driver name and Sequence Number :)
This should do it :
<?php
class SPD {
function SPD($aa) {
foreach ($aa as $k => $v)
$this->$k = $aa[$k];
}
}
function readDatabase($filename) {
// read the XML database of aminoacids
$data = implode("", file($filename));
$parser = xml_parser_create();
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
xml_parse_into_struct($parser, $data, $values, $tags);
xml_parser_free($parser);
// loop through the structures
foreach ($tags as $key => $val) {
if ($key == "TRIP") {
$molranges = $val;
// each contiguous pair of array entries are the
// lower and upper range for each molecule definition
for ($i = 0; $i < count($molranges); $i+=2) {
$offset = $molranges[$i] + 1;
$len = $molranges[$i + 1] - $offset;
$tdb[] = parseMol(array_slice($values, $offset, $len));
}
} else {
continue;
}
}
return $tdb;
}
function parseMol($mvalues) {
for ($i = 0; $i < count($mvalues); $i++) {
if(isset($mvalues[$i]["value"])) {
$mol[$mvalues[$i]["tag"]] = $mvalues[$i]["value"];
}
}
return new SPD($mol);
}
$db = readDatabase("test.xml");
if (is_array($db)) {
foreach ($db as $item) {
echo 'ITEM 1 : ' . "\n<br/>";
echo '---------------' . "\n<br/>";
echo 'DRIVERNAME : ' . $item->DRIVERNAME . "\n<br/>";
echo 'SEQUENCENO : ' . $item->SEQUENCENO . "\n\n<br/><br/>";
}
}
?>
I'm using IMAP to do some data entry by reading a mailbox. The code works perfectly for almost all emails except for one instance where the attachment's filename contains asterisk (*) character, in such case the code can't grab the file (or more exactly, the PDF attachment is not readable)
The code that I write to fetch email content (including getting PDF attachment) is:
public function fetchBody ($message_num) {
if ($this->imap) {
$body = '';
$body_type = 'text';
$attachments = array();
$structure = imap_fetchstructure($this->imap, $message_num);
//pr($structure);
if (!$structure) {
return false;
} else {
if ($structure->type == 0) {
if (strtolower($structure->subtype) == 'html') {
$body_type = 'html';
}
$body = $this->decodeBody(imap_body($this->imap, $message_num), $structure->encoding, FT_PEEK);
} elseif ($structure->type == 1) {
// Grab the text portion of a multipart email
if (count($structure->parts)) {
foreach ($structure->parts as $i => $part) {
if (strtolower($part->subtype) == 'alternative') {
if (count($part->parts)) {
foreach ($part->parts as $j => $subpart) {
if (strtolower($subpart->subtype) == 'plain' || strtolower($subpart->subtype) == 'text') {
$body = $this->decodeBody(imap_fetchbody($this->imap, $message_num, ($i + 1) . '.' . ($j + 1), FT_PEEK), $subpart->encoding);
}
}
}
} elseif (strtolower($part->subtype) == 'related') {
if (count($part->parts)) {
foreach ($part->parts as $j => $subpart) {
if ( isset($subpart->parts) && count($subpart->parts)) {
foreach ($subpart->parts as $k => $subsubpart) {
if (strtolower($subsubpart->subtype) == 'plain' || strtolower($subsubpart->subtype) == 'text') {
$body = $this->decodeBody(imap_fetchbody($this->imap, $message_num, ($i + 1) . '.' . ($j + 1) . '.' . ($k + 1), FT_PEEK), $subsubpart->encoding);
}
}
}
}
}
} elseif (strtolower($part->subtype) == 'plain' || strtolower($part->subtype) == 'text') {
$body = $this->decodeBody(imap_fetchbody($this->imap, $message_num, $i + 1, FT_PEEK), $structure->encoding);
} else {
CakeLog::write('debug', print_r($part, true));
if (($part->type >= 2 && $part->type <= 7) && (!isset($part->parts))) {
$attachments[] = $this->processAttachment($part, $i);
}elseif (strtolower($part->subtype) == 'mixed' || (count($part->parts) && $part->subtype == 'RFC822')) {
if (count($part->parts)) {
foreach ($part->parts as $j => $subpart) {
if (strtolower($subpart->subtype) == 'plain' || strtolower($subpart->subtype) == 'text') {
$body = $this->decodeBody(imap_fetchbody($this->imap, $message_num, ($i + 1) . '.' . ($j + 1) . '.' . ($k + 1), FT_PEEK), $mixedsubpart->encoding);
}else{
if ($subpart->type >= 2 && $subpart->type <= 7) {
$attachments[] = $this->processAttachment($subpart, $i);
}
}
}
}
}
}
}
}
}
}
$data['body'] = $this->cleanUp($body, $structure);
$data['body_type'] = $body_type;
$data['attachments'] = $attachments;
return $data;
} else {
return false;
}
}
Also, this is the debug output when the code detects attachment's filename contains asterisk characters:
2016-02-19 17:13:46 Debug: stdClass Object
(
[type] => 2
[encoding] => 0
[ifsubtype] => 1
[subtype] => RFC822
[ifdescription] => 0
[ifid] => 0
[lines] => 343
[bytes] => 25561
[ifdisposition] => 0
[ifdparameters] => 0
[ifparameters] => 0
[parameters] => stdClass Object
(
)
[parts] => Array
(
[0] => stdClass Object
(
[type] => 3
[encoding] => 3
[ifsubtype] => 1
[subtype] => PDF
[ifdescription] => 1
[description] => *MEA - Invoice No. 91135811 *
[ifid] => 0
[bytes] => 23602
[ifdisposition] => 0
[ifdparameters] => 0
[ifparameters] => 1
[parameters] => Array
(
[0] => stdClass Object
(
[attribute] => name
[value] => *MEA - Invoice No. 91135811 *.pdf
)
)
)
)
)
I can still save all the information (title, filename, etc) to the database though, only the file when saved to the server is unreadable for some reason (see attached photo)
Has anybody come across this situation before?
Looking on how to remove useless junk from result like:
] => Array ( [] =>
My PHP code:
<?php
$url = 'http://api.wolframalpha.com/v2/query?input=planes+seen+from+dallas&appid=2UJ62E-Q6RT3T89P8';
$parser = new XMLReader;
$parser->open($url);
while ($parser->read()) {
if ($parser->nodeType === XMLReader::ELEMENT) {
while ($parser->name === 'pod' && $parser->getAttribute('title') !== 'Result')
$parser->next('pod'); // jump to the next pod node
if ($parser->name === 'plaintext') {
$str = $parser->readString();
$parser->close();
break;
}
}
}
$lines = explode("\n", $str);
$result = array();
foreach ($lines as $line) {
$fields = explode(' | ', $line);
$flight = array_shift($fields);
$flight = $flight . "<hr>"; //DELETE IF DOESN'T WORK
if ($flight === '')
$cols = $fields;
elseif (isset($fields[1])) {
$result[$flight][$cols[0]] = $fields[0];
$result[$flight][$cols[1]] = $fields[1];
}
}
print_r($result);
?>
Sample output:
Array ( [] => Array ( [] => slant distance ) [Atlantic Southeast Airlines flight 5520] => Array ( [] => 23 miles SW ) [Volaris flight 940] => Array ( [] => 30 miles NNW ) [American Airlines flight 386] => Array ( [] => 14 miles NW ) [American Airlines flight 296] => Array ( [] => 27 miles W ) [Central Air Southwest flight 7] => Array ( [] => 6.5 miles WSW ) )
At each break, there's a <hr> tag, not very important though.
Try this:
<?php
$url = 'http://api.wolframalpha.com/v2/query?input=planes+seen+from+dallas&appid=2UJ62E-Q6RT3T89P8';
$parser = new XMLReader;
$parser->open($url);
while ($parser->read()) {
if ($parser->nodeType === XMLReader::ELEMENT) {
while ($parser->name === 'pod' && $parser->getAttribute('title') !== 'Result')
$parser->next('pod'); // jump to the next pod node
if ($parser->name === 'plaintext') {
$str = $parser->readString();
$parser->close();
break;
}
}
}
$lines = explode("\n", $str);
$result = array();
foreach ($lines as $line) {
$fields = explode(' | ', $line);
$flight = array_shift($fields);
$flight = $flight . "<hr>"; //DELETE IF DOESN'T WORK
if ($flight === '')
$cols = $fields;
elseif (isset($fields[1])) {
$result[$flight][$cols[0]] = $fields[0];
$result[$flight][$cols[1]] = $fields[1];
}
}
foreach($result as $key=>$value)
{
echo $key;
foreach($value as $value1){
echo $value1;
echo " ";
}
}
I have an array that's being passed to a foreach and even though I've used foreach's hundred's of times before, I can't figure out why this is giving me the error, Warning: Invalid argument supplied for foreach()
switch($searchby){
case 0: // Name
print_r($data);
foreach($data as $key => $i){
if($key % 2 == 0 && $i == $searchfor){
$success = TRUE;
$matches[] = array('name' => $i, 'value' => $data[$key+1]);
}
}
break;
}
The print_r prints a normal array, for instance (an actual example):
Array
(
[0] => Username
[1] => 4567
[2] => Password
[3] => 4567
[4] => Name
[5] => 4567
[6] => Age
[7] => 4567
[8] => Country
[9] => 4567
[10] => Type
[11] => Register
)
---- Since apparently it works, here's the entire callstack with the stack marked with <------: ----
/// Main.js ///
$("form#Register").submit(function () {
event.preventDefault();
$.post("php/proc.php",{'Command':'registerUser','Data':$(this).serialize()},function (data) { // <---- Original call
console.log(data);
});
return false;
});
// proc.php //
echo json_encode($MainLib->registerUser($db, $data)); // <--------- #1
class MainLib
{
public function registerUser($db, $data){
$pword = $this->hashpword($db, $result1[0]['value'], $result2[0]['value'], 'Register'); // <---------------- #2
}
public function hashpword($db, $data){
$uname = $this->searchData(0,'Username',$data); // <----------- #3
$pword = $this->searchData(0,'Password',$data);
$type = $this->searchData(0,'Type',$data);
switch($type){
case 'Register':
$salt = uniqid(rand(0,99999999),TRUE);
$db->query("UPDATE `Users` SET `salt`='" . $salt . "' WHERE `Username`='" . $uname . "'");
echo "UPDATE `Users` SET `salt`='" . $salt . "' WHERE `Username`='" . $uname . "'";
break;
$result = $db->query("SELECT * FROM `Users` WHERE `Username`='" . $uname . "'");
while($row = $result->fetch_assoc()){
$salt = $row['salt'];
}
}
$salt = base_convert($salt, 26, 10);
$pword = base_convert($pword, 26, 10);
$new_pword = $pword * $salt;
$new_pword = base_convert($new_pword, 10, 17);
$pword = hash('sha512',$new_pword);
return $pword;
}
public function searchData($searchby, $searchfor, $data){
$success = FALSE;
switch($searchby){
case 0: // Name
print_r($data);
foreach($data as $key => $i){ // <--------- ERROR
if($key % 2 == 0 && $i == $searchfor){
$success = TRUE;
$matches[] = array('name' => $i, 'value' => $data[$key+1]);
}
}
break;
case 1: // Value
foreach($data as $key => $i){
if($key % 2 == 0 && $data[$key+1] == $searchfor){
$success = TRUE;
$matches[] = array('name' => $i, 'value' => $data[$key+1]);
}
}
break;
}
if($success) return $matches;
return FALSE;
}
}
this might not be the right answer, i just want to know if this will suppress the error:
switch($searchby){
case 0: // Name
if(is_array($data)) { //--> add this validation
print_r($data);
foreach($data as $key => $i){
if($key % 2 == 0 && $i == $searchfor){
$success = TRUE;
$matches[] = array('name' => $i, 'value' => $data[$key+1]);
}
}
} else {
die('Invalid Array!');
}
break;
}
try to add is_array condition if it could still print the value of $data and able to continue your script.
I have this code, which is parcially working... I'm trying to do this:
Array
(
[servicio_id 1] => Array
(
[peticion_id 1] => Array
(...)
[peticion_id 2] => Array
(...)
[peticion_id 3] => Array
(...)
)
[servicio_id 2] => Array
(
[peticion_id 1] => Array
(...)
[peticion_id 2] => Array
(...)
[peticion_id 3] => Array
(...)
)
)
So each [servicio_id] has it's [peticion_id] with its own values... the problem is that my code actually set the same values inside every [peticion_id] array, increasing it's size as long as the loop is running... Any advice on how to clear and start again the [peticion_id] array once the [servicio_id] is finished?
Thank you in advice
while($row = sqlsrv_fetch_array($sqlQuery)) {
if($row['peticion_id'] == 0) {
$ok[] = round($row['valor'], 3);
if($row['media_ok'] == null) {
$medias_ok = array("0", "0", "0", "0");
} else {
$medias_ok = Umbrales::getValues($row['media_ok'], $row['media']);
}
$max_ok[] = $medias_ok[1];
$min_ok[] = $medias_ok[0];
}
if($row['peticion_id'] == 1) {
$ko[] = round($row['valor'], 3);
if($row['media_ok'] == null) {
$medias_ko = array("0", "0", "0", "0");
} else {
$medias_ko = Umbrales::getValues($row['media_ok'], $row['media']);
}
$max_ko[] = $medias_ko[2];
}
if($row['peticion_id'] == 2) {
$rt[] = round($row['valor'], 3);
if($row['media_ok'] == null) {
$medias_rt = array("0", "0", "0", "0");
} else {
$medias_rt = Umbrales::getValues($row['media_ok'], $row['media']);
}
$max_rt[] = $medias_rt[3];
}
$datos[$servicios[$row['servicio_id']]] = array(
"OK" => $ok,
"KO" => $ko,
"RT" => $rt,
"UMBRAL_MIN_OK" => $min_ok,
"UMBRAL_MAX_OK" => $max_ok,
"UMBRAL_MAX_KO" => $max_ko,
"UMBRAL_MAX_RT" => $max_rt
);
}
You need to clear the array on each loop.
After you while it should read:
while($row = sqlsrv_fetch_array($sqlQuery)) {
$ok = array();
$ko = array();
$rt = array();
$min_ok = array();
$max_ok = array();
$max_ko = array();
$max_rt = array();
if($row['peticion_id'] == 0) {