PHP - Sort Array Of Objects By Date In Objects
Hello all!
I have this array of objects:
Array ( [0] => stdClass Object ( [first_name] => test [last_name] => test [title] => test [id] => 34 [type] => 4 [manager] => 4 [email] => p@yahoo.com [date] => 2014-09-21 07:23:12 [status] => 2 [approval_date] => 2014-09-21 07:31:10 [assessment_id] => 1 [supervisor_approval] => 1 [manager_approval_date] => 2014-09-21 07:31:27 [mainmanger] => 3 ) [1] => stdClass Object ( [first_name] => test [last_name] => test [title] => test [id] => 34 [type] => 4 [manager] => 4 [email] => p@yahoo.com [date] => 2014-09-20 07:39:55 [status] => 2 [approval_date] => 2014-09-20 07:40:41 [assessment_id] => 3 [supervisor_approval] => 1 [manager_approval_date] => 2014-09-20 07:41:07 [mainmanger] => 3 ) [2] => stdClass Object ( [first_name] => jimmy john john [last_name] => john [title] => Lorad and Master [id] => 32 [type] => 4 [manager] => 3 [email] => j@j.com [date] => 2014-09-21 07:38:50 [status] => 2 [approval_date] => 2014-09-19 07:39:25 [assessment_id] => 2 [supervisor_approval] => 1 [manager_approval_date] => 2014-09-19 07:39:25 [mainmanger] => 0 ) )Where "id" = the user ID. If there are two or more entries for a user, I want to remove all but the most recent by the "approval_date",... So for the above example it would return: Array ( [0] => stdClass Object ( [first_name] => test [last_name] => test [title] => test [id] => 34 [type] => 4 [manager] => 4 [email] => piznac@yahoo.com [date] => 2014-09-21 07:23:12 [status] => 2 [approval_date] => 2014-09-21 07:31:10 [assessment_id] => 1 [supervisor_approval] => 1 [manager_approval_date] => 2014-09-21 07:31:27 [mainmanger] => 3 ) [1] => stdClass Object ( [first_name] => jimmy john john [last_name] => john [title] => Lorad and Master [id] => 32 [type] => 4 [manager] => 3 [email] => j@j.com [date] => 2014-09-21 07:38:50 [status] => 2 [approval_date] => 2014-09-19 07:39:25 [assessment_id] => 2 [supervisor_approval] => 1 [manager_approval_date] => 2014-09-19 07:39:25 [mainmanger] => 0 ) )I'm having a hard time wrapping my head around this concept, so I don't have any example code. And I don't really need or expect someone to code this for me,. just a push in the right direction would be awesome. Similar TutorialsI have the following three tables (and also delta_point and hist_point which are purposely left out and just mentioned for context). Before going down the Doctrine ORM long curvy road, aggrType was just used to restrict possible values so that I didn't need to use MySQL's ENUM, but now I am thinking there may be value to making it an entity and include some methods (and a second reason because I still can't figure out how to make Doctrine create a FK constraint yet not populate the parent entity with a AggrType object). point -id (int PK) -data -dType /* descriminator. Options are AggregatePoint, DeltaPoint, and HistoricPoint */ aggr_point -id (int PK, FK to point) -aggrType (char FK to aggrType) -data aggrType -type (char PK) /* there are about five types */ I have a service to create a new point based on the provided desired type and user data. I don't like the switch statement to determine which type of point to create, but don't know a better way. Also my entity is responsible to provide the appropriate validation rules for the given point type which might not be considered proper but it seems to work for me. Any constructive criticism is welcomed. <?php namespace NotionCommotion\PointMapper\Api\Point; use NotionCommotion\PointMapper\Domain\Entity\Point; class PointService { public function create(string $type, array $params):integer { $class=[ 'aggr'=>'AggregatePoint', 'delta'=>'DeltaPoint', 'hist'=>'HistoricPoint', ][$type]; //$class='Point\\'.$class; //This doesn't seem to be possible and I needed to use the fully qualifed name without the short cut used namespace. $class='\\Greenbean\Datalogger\Domain\Entity\Point\\'.$class; $point=new $class(); $validator=$this->getValidator($point); $params=$validator->sanitize($params); $validator->validate($params); $point->setAccount($this->account); $point->populate($params, $this->em); //Will be addressed later $this->em->persist($point); $this->em->flush(); $point->setIdPublic($this->em->getRepository(Point\Point::class)->getPublicId($point->getId())); return $point->getIdPublic(); } } Now, this is the part I am struggling with the most. I only have one service to create any type of point, so I do wish to put a bunch of if/thens in it and instead move logic to the individual point type being created. The AggrPoint in question requires a sub-point and I don't think it is appropriate to inject the entity manager into a point entity and as an alternative solution find an existing point which is associated with the account which resides in the new AggrPoint. Maybe not appropriate, but it works. This type of point also has a sub-object AggrType as discussed at the very beginning of this post, so I first attempt to create a new one from scratch, but that doesn't work and I need to set $aggrType with an existing one. As an alternative, I passed the entity the entity manager, but as stated I think this is a bad idea. Any recommendations where to go from here? Thank you namespace NotionCommotion\PointMapper\Domain\Entity\Point; class AggregatePoint extends Point { public function populate(array $params, \Doctrine\ORM\EntityManager $em):\NotionCommotion\PointMapper\Domain\Entity\Entity{ $criteria = \Doctrine\Common\Collections\Criteria::create() ->where(\Doctrine\Common\Collections\Criteria::expr()->eq("id_public", $params['pointId'])); if(!$subpoint = $this->getAccount()->getPoints()->matching($criteria)->current()){ throw new \Exception("Invalid subpoint ID $params[pointId]"); } $this->setSubpoint($subpoint); //This won't work since I must use an existing AggregateType and not create a new one $aggrType=new AggregateType(); $aggrType->setType($params['aggrType']); //This just seems wrong and I shouldn't be passing the entity manager to an entity $aggrType=$em->getRepository(AggregateType::class)->findOneBy(['type'=>$params['aggrType']]); $this->setAggregateType($aggrType); unset($params['pointId'], $params['aggrType']); // parent::populate($params) not shown, but it basically calles appropriate setters based on the property name return parent::populate($params); } public function getValidatorRules():array { return $this->filesToArr(['/point/base.json', '/point/aggr.json']); } }
How do I access objects inside an array of database results? I have a method that returns MySQL results as an array "$projects". Running print_r($projects) gives me this: array(1) ( "projects" => object Database_MySQL_Result(6) { protected _internal_row => integer 0 protected _query => string(875) "SELECT [skipping remainder of long query]" protected _result => resource(mysql result) protected _total_rows => integer 53 protected _current_row => integer 0 protected _as_object => string(13) "Model_Project" } ) If I do this: foreach($projects as $project) { echo $project->PROJECT_NAME; } I get "Undefined property: Database_MySQL_Result::$PROJECT_NAME" If I do this: foreach($projects as $project) { echo $project[0]; } the browser will display projects.id for the first returned row *only* echo $project[1] returns the project.id for the second row only. And so on. Each returned row contains over a dozen cells. It's almost as if I'm referring to the array incorrectly, or referring to the wrong array. I feel as though I'm making a very simple (and perhaps dumb) mistake here, but can't quite figure out what it is. Thanks. Phew, okay, I'm at my wits end on how to accomplish this task. My client wants a forum program, but she wants it different from normal in that the forum page won't show just the main threads where you would have to click to see the replies, etc - she wants the forum page to display threads and replies in a tiered fashion. Something like this: Code: [Select] - Thread 1 - Reply 1-1 - Reply 1-1-1 - Reply 1-2 - Reply 1-3 - Reply 1-3-1 - Reply 1-3-1-1 - Reply 1-3-1-1-1 - Reply 1-3-1-2 - Reply 1-3-2 - Thread 2 - Thread 3 - Reply 3-1 etc So, the threads should be arranged in order of their property timeLastChanged (which is updated on replies to it, replies to replies of it, edits, etc) which produces the "bumping" functionality. Then the replies under it should be arranged in order of their property timeStarted (which is the timestamp of when it got created). Now, I have the script so far to the point where I have 3 arrays of objects (stickyObjs, mainsObjs, replyObjs) and these objects are instances of Post with their properties being their database values (author, timeStarted, subject, etc). Now, I have thought to arrange these arrays into one big array of objects in the order that they should appear on the page (don't worry about the indent, that's done elsewhere.) Anyway, how would I go about sorting these arrays into one big array of objects in the order they should appear with those two sorting criteria above (sorting criteria is stickies, 1st main in the order of last available timeLastChanged, any replies to mains, replies to replies, ad nauseum in order of timeStarted, then the next main in the order of timeLastChanged, etc.) I have gone through many possible ways, all of which are incredibly complex and involve many copies of arrays and pointers to objects in arrays and iteration counters and GAH! Does anyone know of an easy way to accomplish this sorting? Here is what I have so far: Code: [Select] class Category { public $title; public $majCatID; public $catID; public $modLevel; public $postingLevel; public $hostedByUID; public $order; public $shortName; public $info; public $stickyObjs; public $mainsObjs; public $replyObjs; private $database; public function __construct($catID) { $this->database = new TBDatabase; $result = $this->database->getIntRow(CAT_TABLE, 'catID', $catID); $row = $this->database->fetchAssoc($result); $this->title = $row['title']; $this->majCatID = $row['majCatID']; $this->catID = $row['catID']; $this->modLevel = $row['modLevel']; $this->postingLevel = $row['postingLevel']; $this->hostedByUID = $row['hostedByUID']; $this->order = $row['order']; $this->shortName = $row['shortName']; $this->info = $row['info']; $this->pointer = 0; } public function sortPosts() { $table = $this->shortName."_threads"; $this->getStickyObjs(); $numStickies = count($this->stickyObjs); $this->getMainObjs(); $numMains = count($this->mainsObjs); $this->getReplyObjs(); $numReplies = count($this->replyObjs); } private function getStickyObjs() { $result = $this->database->getPostResources($this->shortName, $this->catID, "AND isSticky = 1"); if (!$result) { $this->stickyObjs = false; return; } $i = 1; while ($row = $this->database->fetchAssoc($result)) { $this->stickyObjs[$i] = new Post($row); $i++; } return; } private function getMainObjs() { $result = $this->database->getPostResources($this->shortName, $this->catID, "AND isReply = 0"); if (!$result) { $this->mainsObjs = false; return; } $i = 1; while ($row = $this->database->fetchAssoc($result)) { $this->mainsObjs[$i] = new Post($row); $i++; } return; } private function getReplyObjs() { $result = $this->database->getPostResources($this->shortName, $this->catID, "AND isReply != 0"); if (!$result) { $this->replyObjs = false; return; } $i = 1; while ($row = $this->database->fetchAssoc($result)) { $this->replyObjs[$i] = new Post($row); $i++; } return; } } Thanks! Originally, I would get both, and unfortunately would inconsistently use both. Then, I wanted more consistently, so configured php.ini to only return objects as I felt accessing them was more concise. And then later, I found myself needing arrays more often, and initially would just typecast them to arrays but eventually my standard was to set the PDO's fetch style to an array. And now I find myself almost always explicitly requesting arrays and occasionally requesting columns or named values. Do you configure ATTR_DEFAULT_FETCH_MODE, and if so to what? PS. Anyone use FETCH_CLASS, FETCH_INTO or FETCH_NUM? If so, what would be a good use case? Hi,
i have an issue to sort gallery photos by date. Right now its sort by Value (Name).
here is the code
index.php contains :
<div> <?php foreach($categories_array as $photo_category=>$photos_array){?> <?php $category_thumbnail = $gallery_url."/layout/pixel.gif"; if(file_exists('files/'.$photo_category.'/thumbnail.jpg')){ $category_thumbnail = $gallery_url.'/'.$photo_category.'/thumbnail.jpg'; } $category_url = $gallery_url.'/'.$photo_category; ?> <span class="category_thumbnail_span" style="width:<?php echo $settings_thumbnail_width;?>px; height:<?php echo $settings_thumbnail_height+20;?>px;"> <a class="category_thumbnail_image" href="<?php echo $category_url;?>" style="width:<?php echo $settings_thumbnail_width;?>px; height:<?php echo $settings_thumbnail_height;?>px; background-image:url('<?php echo $gallery_url;?>/layout/lens_48x48.png');" title="<?php echo htmlentities(ucwords(str_replace('-', ' ', $photo_category)));?>"> <img src="<?php echo $category_thumbnail;?>" width="<?php echo $settings_thumbnail_width;?>" height="<?php echo $settings_thumbnail_height;?>" alt="<?php echo htmlentities(ucwords(str_replace('-', ' ', $photo_category)));?>" /> </a> <a class="category_thumbnail_title" href="<?php echo $category_url;?>" title="<?php echo htmlentities(ucwords(str_replace('-', ' ', $photo_category)));?>"> <?php echo htmlentities(str_replace('-',' ', truncate_by_letters($photo_category, 16, '..')), ENT_QUOTES, "UTF-8");?> (<?php echo count($photos_array);?>) </a> </span> <?php } ?> </div>the sort function : ksort($categories_array); Hello, I'm making a imagegallery and when someone upload a new image that image has to appear as first picture of the gallery. I'm using an array for the files, but how can I sort the files on date, newest first.? <?php $n = 0; $pathToThumbs = "images/tekeningen/"; $dir = opendir( $pathToThumbs ); while (false !== ($fname = readdir($dir))){ // strip the . and .. entries out if ($fname != '.' && $fname != '..'){ $tekeningen[$n] = $fname; } echo $tekeningen[$n]."<br />"; $n = $n +1; } closedir( $dir ); ?> I found solutions with ksort and filemtime, but I don't understand them and/or they didn't work for me. Hi I am new to PHP and I need to create an array and add both books to the array and than loop through the array this is where I am having trouble if the price of a book is less than $20.00 output the book’s name and price if the book’s title comes after the letter R in the alphabet output the book’s title. I am getting these error:
Notice: Trying to get property 'price' of non-object in C:\xampp\htdocs\PHP objects\books.php on line 45 My code is:
<?php
// Methods
$first_book = new Book();
foreach ($book as $bookItem) { Any help will be very much appreciated Thank you I found it helpful to configure all my objects in one or several bootstrap scripts. Before doing so, I would often find myself forgetting that I already had written some class which is located deep in some script and recreating it for some other need (granted, composer definitely helped in this regard, but using it wasn't always applicable). <?php $c=new Pimple\Container(getMySettings()); $c['pdo'] = function ($c) { $db = $c['settings']['mysql']; return new \PDO(bla); }; $c['foo'] = function ($c) { return new Foo( $c->get('pdo') ); }; $c['bar'] = function ($c) { return new Bar( $c->get('foo') ); }; It is all good until I find myself needing to create some new instance of some class instead of just passing some common instance to whoever needs it. class Foo { private $pdo; public function __construct(\PDO $pdo) { $this->pdo=$pdo; } public function getSomething():SomeClass { return new SomeClass($this->getAllDataFromDB($GET['id'])); } } class SomeClass { private $arr; public function __construct(array $records) { foreach($records as $record) { $arr[]=new SomeOtherClass($record); } } } I've read that one shouldn't create new objects in a given class's constructor, and while I could instead do so in some class's method and pass the object to the given class's constructor, to me it seems to really be the same thing. The three issues I have with this scenario a Needing to remember that these classes exist as they are hidden deep in some classes. Makes it more difficult to replace one of the classes with some other class in the future. Some duplication of code.Are there other compelling reasons not to do so? Is it worth the effort to do differently? If so, how would you recommend doing so? My thoughts would either to use Pimple's factory() method are create my only factory which also relies on anonymous functions. Maybe something else? $c['someClass'] = $c->factory(function (array $record, Container $c) { return new SomeClass($record); }); Thanks Hi all,
I am working with the following 2 page script: https://github.com/k...hi/php-riot-api. All works well and the data is pulled via the API as intended. However, depending on the data I'm trying to display on screen, the object contains multiple values.
For example:
$r = $test->getSummoner($summoner_id,'name'); print_r($r);outputs their ID and name: {"585897":"TheirName"} Just as the following: $r = $test->getSummonerByName($summoner_name); print_r($r);outputs username, ID, Name, profile icon ID, level, and timestamp: {"theirname":{"id":585897,"name":"TheirName","profileIconId":642,"summonerLevel":30,"revisionDate":1405652924000}} Depending on which function I am calling (on example.php), I would like to be able to split the values so I can echo them throughout a page: Name: <value> ID: <value> Level: <value> etc... Any guidance would be appreciated. In a relational database, you "link" tables together. For example, Customer (parent) ---> Product (child) How do you do that with Objects? I have a "User" class and an "AddressBook" class. A User can have zero or more Addresses (in their AddressBook). If I create a User object and an AddressBook object, I need a way to link them up similar to how they are linked up in the database. Make sense?! TomTees I took an object, and saved it into a database serialized. Code: [Select] $object_here = serialize($theobject); Then later on, I go and I get that data from a database, and try to unserialize it.. Code: [Select] $objecthere = unserialize($row->theobject) And it throws the following error...any advice? Quote Warning: unserialize() [function.unserialize]: Node no longer exists in /path/to/file on line 20 I know it is often frivolous, but sometimes I can't help trying to optimize things, and use the following two methods to create either an object injected with a string or one of a set of objects. For both cases, the class has no setters so there is no chance that the object will later be changed. I first stated doing this in continuously running server applications which I believe makes sense, however, it has leaked over to standard HTTP requests. Please commit good or bad on this approach. Thanks
public static function create(string $unit):self { static $stack=[]; if(!isset($stack[$unit])) { $stack[$unit] = new self($unit); } return $stack[$unit]; } public static function create(string $class):FunctionInterface { static $stack=[]; if(!isset($stack[$class])) { $stack[$class] = new $class; } return $stack[$class]; }
I have a page in which the print_r ($session) displays the following: Array ( [securityToken] => 23b1f22bffd9f5097878618da57b14a2 [cartID] => [cart] => shoppingCart Object ( [contents] => Array ( ) [total] => 0 [weight] => 0 [cartID] => [content_type] => [free_shipping_item] => 0 [free_shipping_weight] => 0 [free_shipping_price] => 0 ) [navigation] => navigationHistory Object ( [path] => Array ( [0] => Array ( [page] => index [mode] => NONSSL [get] => Array ( [cPath] => 2_9_843_845_852_856_858_863 ) [post] => Array ( ) ) [1] => Array ( [page] => product_info [mode] => NONSSL [get] => Array ( [cPath] => 2_9_843_845_852_856_858_863 [products_id] => 2299 [action] => add_product ) [post] => Array ( ) ) [2] => Array ( [page] => shopping_cart [mode] => NONSSL [get] => [post] => Array ( ) ) [3] => Array ( [page] => checkout_shipping [mode] => NONSSL [get] => [post] => Array ( ) ) [4] => Array ( [page] => checkout_payment [mode] => NONSSL [get] => [post] => Array ( ) ) [5] => Array ( [page] => checkout_confirmation [mode] => NONSSL [get] => [post] => Array ( ) ) [6] => Array ( [page] => checkout_process [mode] => NONSSL [get] => [post] => Array ( ) ) [7] => Array ( [page] => checkout_success [mode] => NONSSL [get] => [post] => Array ( ) ) ) [snapshot] => Array ( ) ) [check_valid] => true [language] => english [languages_id] => 1 [languages_code] => en [currency] => USD [today_is] => 2010-11-26 [updateExpirations] => 1 [session_counter] => 1 [new_products_id_in_cart] => 2299 [valid_to_checkout] => 1 [cart_errors] => [customer_id] => 2 [customer_first_name] => test [customer_default_address_id] => 2 [customer_country_id] => 223 [customer_zone_id] => 2 [customers_authorization] => 0 [messageToStack] => [payment_attempt] => 1 ) What I need to do is loop through the navigationHistory Object , grab the product id, and then get the cPath for that particular product id. I have worked with sessions a lot, but I cannot seem to ever get the session object and loop thing down. At this point I am ripping out my hair trying to figure out what is most likely a simple solution to this - can anyone help me? Hello, I want to make a list with 2 columns on one of my pages with link to categories on my page. But they appear in only one column (on below the other) and i want them to be like: Pictures Videos Pictures2 Videos2 These are my codes <li> <a href="user_album_add.php">Pictures</a> <li> <a href="user_album2_add.php">Pictures2</a> <li> <a href="user_video_add.php">Video</a> <li> <a href="user_video2_add.php">Video2</a> What should i do? Thank you! I can post some code once I am back at my laptop but for now thinking about this is keeping me awake in bed and all I have handy is my phone. Anyway, I am new to OOPHP. I have a class that I created. I have two objects/instances of it, each using some of the same and some different methods within the class. When I run the page either of the instances works great alone but I get the white screen of death when I try to use both instances at the same time. Any ideas or places I should start? Ever since I started using OOP this past week, I have not been able to go back to the old "procedural" methods. HOwever, I seem to be stuck on creating a mysql connection that I can reuse in all of my classes. After I set up a connection to mysql using the mysqli object, I am unable to use the mysqli in other objects. Code: [Select] $mysqli = new mysqli(.....); class new_class { function quickQuery () { $mysqli->query('some query') } } Obviously, this doesn't work, because $mysqli is not defined within that functions scope. One way, is to use global keyword. Code: [Select] global $mysqli However, globals "are the root of all evil" and simply go against the idea of encapsulation in OOP. What's a way around this? HOWEVER: 1) I still want to use the mysqli object 2) I don't want to reference the $link of the db each time I instantiate a new class .... Maybe I'm asking too much? And I've google for the past hour or so. Singleton seems interesting but it requires the creation of a new db connection class. I want to use the mysqli object. Hi I am trying to connect to my database but i am having some problems where the server( WAMP) crashes and does not load this page. here is the php coding
<?php $db = new PDO("mysql:host=localhost;dbname=test;port=80", "root", ""); var_dump($db);when i run this no error comes the page doesnt load. anyone know why? when using PDO do i have to do some sort of configuration changes to wamp? i have even changed the directory of the file and still same issue. any suggestions would be wonderful. Hi all,
I was just wondering is this possible what I'm trying to do?
Models can only store one object at a time...
I'm trying to access multiple objects via one model...
<?php class users extends Model { protected $username; protected $firstname; protected $secondname; protected $age; // There will be more here... public function __construct($id = NULL) { if($id != NULL) { $this->username = $sql->getUsername($id); $this->firstname = $sql->getFirstname($id); $this->secondname = $sql->getSecondname($id); $this->age = $sql->getAge($id); } } public function numOfUsers() { $num = $sql->countAllUsers($query); return $num; } public function getUsername() { return $this->username; } public function getFirstname() { return $this->firstname; } public function getSecondname() { return $this->secondname; } public function getAge() { return $this->age; } }; class UsersView extends View { $users = new users(); for($i = 0; $i < $users->numOfUsers(); $i++) { $user = new users($i); echo "Username: {$user->getUsername()}"; echo "Username: {$user->getFirstname()}"; echo "Username: {$user->getSecondname()}"; echo "Username: {$user->getAge()}"; } }; ?> I have gotten into the habit of freeing MySQLi result objects once they are no longer needed. However, I'm curious about the cases where multiple MySQLi objects are being used. I think this is what it is called... I having a brain fart... And I don't play with classes that much... Plus I have been playing with trying to get pdf's to output correctly so my brain is toasty.... I'm trying to parse DICOM (medical file format) files and I have this class and I want to setup an array to pull what fields I want. Code: [Select] <?php require '../dicomparser/nanodicom.php'; $filename = 'B4IBG5A0'; // 5) Load simple and print certain value try { //echo "5) Load simple and print certain value\n"; $dicom = Nanodicom::factory($filename); $dicom->parse(); //echo $dicom->profiler_diff('parse').'<br>'; echo 'Patient Name: '.$dicom->value(0x0010, 0x0010).'<br>'; echo 'Operators Name: '.$dicom->value(0x0010, 0x0040).'<br>'; echo 'Patient ID: '.$dicom->value(0x0010,0x0020).'<br>'; unset($dicom); } catch (Nanodicom_Exception $e) { echo 'File failed. '.$e->getMessage()."\n"; } //} ?> So what I want to do is have the array contain 'Patient Name' => '(0x0010, 0x0010)' etc... And have it something like this so I don't have to echo all the lines I want. Code: [Select] foreach ($array as $key => $value) { echo $key': '.$dicom->value.$value.'<br>'; } I can't get it to work... I remember figuring it out once before but that was over a year ago... And I don't have the code I wrote. I know it's something simple stupid. like $$ or [] i'm not getting the combination right. Thanks in advance... |