I have this object:
foreach(range(1,$oc->num_users) as $num) {
$user = 'user' . $num;
$$user = mysql_fetch_object(mysql_query("SELECT user".$num.", user".$num."_ready, FROM oc_db WHERE leader='".$_SESSION['username']."' "));
This gives objects named user1..X
later I have a simular function like this, where I use the $$user->$user that represent a username to connect to the db to get additional information.
$$user = mysql_fetch_object(mysql_query("SELECT x, y, z FROM user_db WHERE username='".$$user->$user."' "));
This also makes objects named user1..X, but instead of replacing the object created earlier I want to append this values to the object I created in the first function. $$user is the name of the objects. I would like to do something like $$user .= fetch_object in the last function, but off course it's not that simple.
In order to append one object to another you simply need to iterate through the first object and then assign each property you find to the second one:
$tmp = mysql_fetch_object(mysql_query("SELECT x, y, z FROM user_db WHERE username='".$$user->$user."' "));
foreach ($tmp as $key => $value) {
$$user->$key = $value;
}
As a couple of asides, if you are trying to access the user property of the object, then you should use $$user->user, as $$user->$user will be trying to access a numbered property (e.g. for object $user12, you're trying to access $user12->user12). I would also consider using an array, as fredley suggested (i.e. use $user[$num] instead of $user = 'user'.$num).
To approach your original question, instead of using the .= concatenation assignment operator, you could try adding a method to your user class, such as append, then using it to append the fetched object to your current object like $user->append( fetch_object(...));. In the append method, you can define your own rules for how a fetched object is added to your current user object.
Related
I got this code from the internet. I don't know how the
$databases = current($res->toArray());
is working in the code. I am new in MongoDB and PHP. How is the current function able to retrieve all values? What exactly is executeCommand retrieving?
$mng = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$listdatabases = new MongoDB\Driver\Command(["listDatabases" => 1]);
$res = $mng->executeCommand("admin", $listdatabases);
$databases = current($res->toArray());
foreach ($databases->databases as $el) {
echo $el->name . "\n";
}
$res = $mng->executeCommand("admin", $listdatabases); executes the listDatabases command and assigns the result to $res. The result is a Cursor object, which has a toArray method.
The result of some $res->toArray() is, not surprisingly, an array. Its first element is an object that contains the list of databases.
Now, current is not a function specific to MongoDB. It's a standard PHP function that returns the current element of an array. Since the array was just created, the current element is the first element, the object that contains the list of databases.
So $databases = current($res->toArray()); gets you an object ($databases) that has a property databases which contains an array of database objects that you can iterate with foreach.
I've just started out learning PHP/JSON and I've kind of worked out how to output an array from an json file. My aim is to output all the album titles in <li>'s (in this case they are called collectionName in the json file). I think I maybe going about it the wrong way though.
$artistId = '644708';
$otherAlbumsURL = 'http://itunes.apple.com/lookup?id='. $artistId .'&entity=album';
$a = (array)json_decode(file_get_contents($otherAlbumsURL));
var_dump($a);
If you want an array, just use:
$a = json_decode(file_get_contents($otherAlbumsURL), true);
var_dump($a);
Setting the second parameter in json_decode to TRUE will give you an associative array instead of an object.
Judging from the response of the URL, you'll need to loop through the result like this in order to get any available collection names (the first array element doesn't contain a collection name because it is information about the artist. i.e. it isn't an album):
$artistInfo = $a['results'][0]; //Assign artist info to its own variable.
unset($a['results'][0]); //Delete artist info from the array.
//Loop through the results
foreach($a['results'] as $result){
//$result['collectionName'] has the collection name.
echo $result['collectionName'] . '<br>';
}
I'm accessing an mssql db in PHP and creating the connection as a new COM() object. My query runs perfectly fine. When I do the query in Microsoft SQL Server 2008, everything looks great, the dates/times show up in columns and are readable.
But when I run the same query and return the results in PHP, I go to iterate through the results like so:
$selected_fields = array("FS.fund_name", "M.media_id", "MT.media_type_name", "modified_date", "file_upload_date", "issued_date", "filename");
//query goes here
$record_set = new COM("ADODB.Recordset");
while(!$record_set->EOF){ //loop through query results and add to inline cache variable
$temp_record = array();
foreach($selected_fields as $fieldname){ //go through fields and add to array
$fieldname_array = explode(".", $fieldname); //separate table and column
$fieldname = $fieldname_array[sizeof($fieldname_array)-1];
$temp_record[$fieldname] = $record_set->fields[$fieldname]->value;
}
print_r($temp_record);
$rs_array[] = $temp_record;
$record_set->movenext();
}
As I print each $temp_record, they end up looking like this:
Array ( [fund_name] => TEST [media_id] => 1001 [media_type_name] => 8937 Tax Forms [modified_date] => variant Object [file_upload_date] => variant Object [issued_date] => variant Object [filename] => form8937test.pdf )
So the dates are some kind of object, and I don't know how to access them in PHP. And when I go to save them as a cache file, they have this value:
variant::__set_state(array())
How can I retrive the date/time in a format that I can then manipulate using PHP? I want to filter them by year, and sort them by most recent.
According to Variant Object documentation, you should be able to access it by
$temp_record['modified_date']->value;
or
$val = (string)$temp_record['modified_date'];
From the same doc:
the variant is converted to a PHP value only when there is a direct
mapping between the types that would not result in a loss of
information. In all other cases, the result is returned as an instance
of the VARIANT class.
So to check if cast is needed, simply check if you have an object of Variant class:
if (is_object($var) && $var instanceof Variant) {
$val = (string)$var;
} else {
$val = $var;
}
There is probably a very simple explanation for this, but I've had this code working for months, and now all of a sudden today it doesn't work.
I retrieve all the rows from a table. I have and object which is an entity model of the table I'm selecting from. As I read the rows from the associative result array, I'm storing each property using "$this->propertyName," and then I'm pushing each object to an array. Before I ended up with an array of objects, now I end up with an array of the same object repeated. Here's a code snippet:
$mdSelectALL_sql="SELECT * FROM member_data";
$mdSelectALL=mysql_query($mdSelectALL_sql,$mdConn);
if(!$mdSelectALL){
die('Error: ' . mysql_error());
}
else{
echo "RETURNING ALL MEMBER DATA RECORDS!!!<br>";
//store all records into array
while($row=mysql_fetch_array($mdSelectALL))
{
$this->mdId=$row['md_id'];
$this->mdFname=$row['md_fname'];
$this->mdLname=$row['md_lname'];
$this->mdEmail=$row['md_email'];
$this->mdTwitter=$row['md_twitter'];
$this->mdFacebook=$row['md_facebook'];
$this->mdMyspace=$row['md_myspace'];
$this->mdPhoneNumber=$row['md_phonenumber'];
$this->mdNotes=$row['md_notes'];
//store records in array
array_push($mdArray,$this);
}//end while
// print_r($mdArray); prints the array and each element is the last record encountered in the SQL retrieval
return $mdArray;
}//end else
My getters and setters look like this for each property:
function get_mdId(){
return $this->mdId;
}
function set_mdId($id){
$this->mdId=$id;
}
And suggestions or ideas?
-TU
Objects are passed around by reference. That means that when you change a value, that value will change everywhere that you have used that object.
As you are storing the same object every time - $this - you end up with an array of references to the same object.
To solve it, you can do:
$mdArray = array();
while($row=mysql_fetch_array($mdSelectALL))
{
$tmp_object = new MyObject; // fill in the name of your object...
$tmp_object->mdId=$row['md_id'];
...
array_push($mdArray, $tmp_object);
}
I'm attempting to use the VirusTotal API to return the virus scan for a certain file. I've been able to get my current PHP code to upload the file to VirusTotal as well as get the results in an array. My question is, how would I get the [detected] value from every virus scanner under the scans object? My PHP code is below as well as a link to the output of the array.
require_once('VirusTotalApiV2.php');
/* Initialize the VirusTotalApi class. */
$api = new VirusTotalAPIV2('');
if (!isset($_GET["hash"])) {
$result = $api->scanFile('file.exe');
$scanId = $api->getScanID($result);
$api->displayResult($result);
} else {
$report = $api->getFileReport($_GET["hash"]);
$api->displayResult($report);
print($api->getSubmissionDate($report) . '<br>');
print($api->getReportPermalink($report, TRUE) . '<br>');
}
http://joshua-ferrara.com/viruscan/VirusTotalApiV2Test.php?hash=46faf763525b75b408c927866923f4ac82a953d67efe80173848921609dc7a44
You would probably have to iterate each object under scans in a for loop and either store them in yet another array or echo them out of just want to print. For example
$detectedA = {nProtect, CAT-QuickHeal, McAfee...nth};
$datContainer = array();
for ($i = 0; i < $api.length ; i++){
//Either store in an array
$api->$scans->detectedA(i)-> detected = $datContainer(i);
//Or echo it all
echo $api->$scans->detectedA(i)->detected;
return true;
}
Granted that's probably not the way you access that object but the idea still applies.
This description of stdClass demonstrates how you can not only store arbitrary tuples of data in an object without defining a class, but also how you can cast an arbitrary object as an array - which would then let you iterate over the sub-objects in your case.
Or, if I've misunderstood your question and you're actually getting an array back from the VirusTotal API and not a stdClass instance, then all you need to do is loop.
Store the scans into an array (of scans), then just loop through the array as usual.
foreach($scans as $scan) echo $scan->detected;
Or, if I'm not quite understanding the question right, is detected an array (or an object)?
Edit because of your comments -
The object returned holds an object of objects, so you need to do some casting.
foreach((array)$scans as $scanObj) {
$scan=(array)$scanObj;
foreach($scan as $anti) {
print $anti->detected; } }