如何将对象数组类定义上的 USort() 作为方法执行?

发布于 2024-10-09 13:18:10 字数 4372 浏览 8 评论 0原文

class Contact{      
    public $name;      
    public $bgcolor;      
    public $lgcolor;      
    public $email;
    public $element;

    public function __construct($name, $bgcolor, $lgcolor, $email, $element) 
    {         
        $this->name = $name;         
        $this->bgcolor = $bgcolor;         
        $this->lgcolor = $lgcolor;         
        $this->email = $email;  
        $this->element = $element; 
    } 

    public static function sortByName(Contact $p1, Contact $p2)
    {
        return strcmp($p1->name, $p2->name);
    }
}  


class ContactList implements Iterator, ArrayAccess 
{     
    protected $_label;     
    protected $_contacts = array();      

    public function __construct($label) 
    {         
        $this->_label = $label;     
    }      

    public function getLabel() 
    {         
        return $this->_label;     
    }      

    public function addContact(Contact $contact) 
    {        
        $this->_contacts[] = $contact;     
    }      

    public function current() 
    {         
        return current($this->_contacts);     
    }      

    public function key() 
    {         
        return key($this->_contacts);     
    }      

    public function next() 
    {         
        return next($this->_contacts);
    }      

    public function rewind() 
    {         
        return reset($this->_contacts);     
    }      

    public function valid() 
    {         
        return current($this->_contacts);     
    }      

    public function offsetGet($offset) 
    {         
        return $this->_contacts[$offset];     
    }      

    public function offsetSet($offset, $data) 
    {         
        if (!$data instanceof Contact)             
            throw new InvalidArgumentException('Only Contact objects allowed in a ContactList');          
        if ($offset == '') 
        {            
            $this->_contacts[] = $data;         
        } else 
        {             
            $this->_contacts[$offset] = $data;         
        }     
    }      

    public function offsetUnset($offset) 
    {        
        unset($this->_contacts[$offset]);    
    }      

    public function offsetExists($offset) {        
        return isset($this->_contacts[$offset]);    
    }

    public function sort($attribute = 'name')
    {
        $sortFct = 'sortBy' . ucfirst(strtolower($attribute));
        if (!in_array($sortFct, get_class_methods('Contact')))
        { 
            throw new Exception('contact->sort(): Can\'t sort by ' . $attribute);
        }
        usort($this->contact, 'ContactList::' . $sortFct);
    }

}     



public function Sort($property, $asc=true)
{
    // this is where sorting logic takes place
    $_pd = $this->_contact->getProperty($property);
    if ($_pd == null)
    {
        user_error('Property '.$property.' does not exist in class '.$this->_contact->getName(), E_WARNING);
        return;
    }
    // set sortDescriptor
    ContactList::$sortProperty = $_pd;
    // and apply sorting
    usort($this->_array, array('ContactList', ($asc?'USortAsc':'USortDesc')));
}

function getItems(){
    return $this->_array;
} 

class SortableItem extends ContactList
{
    static public $sortProperty;

    static function USortAsc($a, $b)
    {
        /*@var $_pd ReflectionProperty*/
        /*
        $_pd = self::$sortProperty;
        if ($_pd !== null)
        {
            if ($_pd->getValue($a) === $_pd->getValue($b))
                return 0;
            else
                return (($_pd->getValue($a) < $_pd->getValue($b))?-1:1);
        }
        return 0;
    }

    static function USortDesc($a, $b)
    {
        return -(self::USortAsc($a,$b));
    }

}

这种方法不断向我发出各种类型的 PHP Warnings: usort() [function.usort]: ,我稍后可以根据需要提供这些警告,以注释掉这些方法和定义,以便测试和修复一些小错误我们的计划。

**$billy 参数已定义。

$all -> addContact($billy);

// --> ended up adding each contact manually above

$all->Sort('name',true);
$items = $all->getItems();
foreach($items as $contact)
{
    echo $contact->__toString();
}

$all->sort();

使用 usort 的原因是按名称按字母顺序重新排列顺序,但不知何故要么说明函数比较需要是一个数组,要么是另一个错误,显然我似乎已经通过了。任何帮助将不胜感激,提前致谢。

class Contact{      
    public $name;      
    public $bgcolor;      
    public $lgcolor;      
    public $email;
    public $element;

    public function __construct($name, $bgcolor, $lgcolor, $email, $element) 
    {         
        $this->name = $name;         
        $this->bgcolor = $bgcolor;         
        $this->lgcolor = $lgcolor;         
        $this->email = $email;  
        $this->element = $element; 
    } 

    public static function sortByName(Contact $p1, Contact $p2)
    {
        return strcmp($p1->name, $p2->name);
    }
}  


class ContactList implements Iterator, ArrayAccess 
{     
    protected $_label;     
    protected $_contacts = array();      

    public function __construct($label) 
    {         
        $this->_label = $label;     
    }      

    public function getLabel() 
    {         
        return $this->_label;     
    }      

    public function addContact(Contact $contact) 
    {        
        $this->_contacts[] = $contact;     
    }      

    public function current() 
    {         
        return current($this->_contacts);     
    }      

    public function key() 
    {         
        return key($this->_contacts);     
    }      

    public function next() 
    {         
        return next($this->_contacts);
    }      

    public function rewind() 
    {         
        return reset($this->_contacts);     
    }      

    public function valid() 
    {         
        return current($this->_contacts);     
    }      

    public function offsetGet($offset) 
    {         
        return $this->_contacts[$offset];     
    }      

    public function offsetSet($offset, $data) 
    {         
        if (!$data instanceof Contact)             
            throw new InvalidArgumentException('Only Contact objects allowed in a ContactList');          
        if ($offset == '') 
        {            
            $this->_contacts[] = $data;         
        } else 
        {             
            $this->_contacts[$offset] = $data;         
        }     
    }      

    public function offsetUnset($offset) 
    {        
        unset($this->_contacts[$offset]);    
    }      

    public function offsetExists($offset) {        
        return isset($this->_contacts[$offset]);    
    }

    public function sort($attribute = 'name')
    {
        $sortFct = 'sortBy' . ucfirst(strtolower($attribute));
        if (!in_array($sortFct, get_class_methods('Contact')))
        { 
            throw new Exception('contact->sort(): Can\'t sort by ' . $attribute);
        }
        usort($this->contact, 'ContactList::' . $sortFct);
    }

}     



public function Sort($property, $asc=true)
{
    // this is where sorting logic takes place
    $_pd = $this->_contact->getProperty($property);
    if ($_pd == null)
    {
        user_error('Property '.$property.' does not exist in class '.$this->_contact->getName(), E_WARNING);
        return;
    }
    // set sortDescriptor
    ContactList::$sortProperty = $_pd;
    // and apply sorting
    usort($this->_array, array('ContactList', ($asc?'USortAsc':'USortDesc')));
}

function getItems(){
    return $this->_array;
} 

class SortableItem extends ContactList
{
    static public $sortProperty;

    static function USortAsc($a, $b)
    {
        /*@var $_pd ReflectionProperty*/
        /*
        $_pd = self::$sortProperty;
        if ($_pd !== null)
        {
            if ($_pd->getValue($a) === $_pd->getValue($b))
                return 0;
            else
                return (($_pd->getValue($a) < $_pd->getValue($b))?-1:1);
        }
        return 0;
    }

    static function USortDesc($a, $b)
    {
        return -(self::USortAsc($a,$b));
    }

}

This approach keeps giving me PHP Warnings: usort() [function.usort]: of all kinds which I can provide later as needed to comment out those methods and definitions in order to test and fix some minor bugs of our program.

**$billy parameters are already defined.

$all -> addContact($billy);

// --> ended up adding each contact manually above

$all->Sort('name',true);
$items = $all->getItems();
foreach($items as $contact)
{
    echo $contact->__toString();
}

$all->sort();

The reason for using usort is to re-arrange the order alphabetically by name but somehow is either stating that the function comparison needs to be an array or another errors which obviously I have seemed to pass. Any help would be greatly appreciated, thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

遗失的美好 2024-10-16 13:18:10

发生这种情况是因为 usort 调用中的变量不是有效的数组。您在任何地方都使用 $this->_contacts ,但您的 usort 行是:

usort($this->contact, 'ContactList::' . $sortFct);

尝试将其更改为:

usort($this->_contacts, 'ContactList::' . $sortFct);

It's happening because the variable inside the usort call is not a valid array. You use $this->_contacts everywhere, but your usort line is:

usort($this->contact, 'ContactList::' . $sortFct);

Try changing that to:

usort($this->_contacts, 'ContactList::' . $sortFct);
So要识趣 2024-10-16 13:18:10
       <?php 
   class Contact{      
   public $name;      
   public $bgcolor;      
   public $lgcolor;      
   public $email;
   public $element;

      public function __construct($name, $bgcolor, $lgcolor, $email, $element) 
      {         
      $this->name = $name;         
      $this->bgcolor = $bgcolor;         
      $this->lgcolor = $lgcolor;         
      $this->email = $email;  
      $this->element = $element; 

      }    
   }  

   class ContactList implements Iterator, ArrayAccess 
   {     
   public $_label;     
   public $_contacts = array();      
        public function __construct($label) 
        {         
        $this->_label = $label;     
        }      
        public function getLabel() 
        {         
        return $this->_label;     
        }      
        public function addContact(Contact $contact) 
        {        
        $this->_contacts[] = $contact;  

        } 



        public function current() 
        {         
        return current($this->_contacts);     
        }      
        public function key() 
        {         
        return key($this->_contacts);     
        }      
        public function next() 
        {         
        return next($this->_contacts);
        }      
        public function rewind() 
        {         
        return reset($this->_contacts);     
        }      
        public function valid() 
        {         
        return current($this->_contacts);     
        }      
        public function offsetGet($offset) 
        {         
        return $this->_contacts[$offset];     
        }      
        public function offsetSet($offset, $data) 
        {         
        if (!$data instanceof Contact)             
        throw new InvalidArgumentException('Only Contact objects allowed in a ContactList');          
        if ($offset == '') 
        {            
         $this->_contacts[] = $data;         
         } else 
         {             
         $this->_contacts[$offset] = $data;         
         }     
         }      
         public function offsetUnset($offset) 
         {        
         unset($this->_contacts[$offset]);    
         }      
         public function offsetExists($offset) {        
         return isset($this->_contacts[$offset]);    
         }








           /* This is the comparing function to be used with usort to make it alphabetically ordered for All Contacts */

           public function sort_by($field, &$arr, $sorting='SORT_DSC', $case_insensitive=true){
           if(is_array($arr) && (count($arr)>0) && ( ( is_array($arr[0]) && isset($arr[0][$field]) ) || ( is_object($arr[0]) && isset($arr[0]->$field) ) ) ){
            if($case_insensitive==true) $strcmp_fn = "strnatcasecmp";
            else $strcmp_fn = "strnatcmp";

            if($sorting=='SORT_DSC'){
             $fn = create_function('$a,$b', '
              if(is_object($a) && is_object($b)){
               return '.$strcmp_fn.'($a->'.$field.', $b->'.$field.');
              }else if(is_array($a) && is_array($b)){
               return '.$strcmp_fn.'($a["'.$field.'"], $b["'.$field.'"]);
              }else return 0;
             ');

            }else if($sorting=='SORT_ASC'){


             $fn = create_function('$a,$b', '
              if(is_object($a) && is_object($b)){
               return '.$strcmp_fn.'($b->'.$field.', $a->'.$field.');
              }else if(is_array($a) && is_array($b)){
               return '.$strcmp_fn.'($b["'.$field.'"], $a["'.$field.'"]);
              }else return 0;
             ');
            }
            usort($arr, $fn);
            return true;
           }else{
            return false;
           }
          }



    }
   ?

通话:

   $all->sort_by('name',$all->_contacts,'SORT_DSC','false');
       <?php 
   class Contact{      
   public $name;      
   public $bgcolor;      
   public $lgcolor;      
   public $email;
   public $element;

      public function __construct($name, $bgcolor, $lgcolor, $email, $element) 
      {         
      $this->name = $name;         
      $this->bgcolor = $bgcolor;         
      $this->lgcolor = $lgcolor;         
      $this->email = $email;  
      $this->element = $element; 

      }    
   }  

   class ContactList implements Iterator, ArrayAccess 
   {     
   public $_label;     
   public $_contacts = array();      
        public function __construct($label) 
        {         
        $this->_label = $label;     
        }      
        public function getLabel() 
        {         
        return $this->_label;     
        }      
        public function addContact(Contact $contact) 
        {        
        $this->_contacts[] = $contact;  

        } 



        public function current() 
        {         
        return current($this->_contacts);     
        }      
        public function key() 
        {         
        return key($this->_contacts);     
        }      
        public function next() 
        {         
        return next($this->_contacts);
        }      
        public function rewind() 
        {         
        return reset($this->_contacts);     
        }      
        public function valid() 
        {         
        return current($this->_contacts);     
        }      
        public function offsetGet($offset) 
        {         
        return $this->_contacts[$offset];     
        }      
        public function offsetSet($offset, $data) 
        {         
        if (!$data instanceof Contact)             
        throw new InvalidArgumentException('Only Contact objects allowed in a ContactList');          
        if ($offset == '') 
        {            
         $this->_contacts[] = $data;         
         } else 
         {             
         $this->_contacts[$offset] = $data;         
         }     
         }      
         public function offsetUnset($offset) 
         {        
         unset($this->_contacts[$offset]);    
         }      
         public function offsetExists($offset) {        
         return isset($this->_contacts[$offset]);    
         }








           /* This is the comparing function to be used with usort to make it alphabetically ordered for All Contacts */

           public function sort_by($field, &$arr, $sorting='SORT_DSC', $case_insensitive=true){
           if(is_array($arr) && (count($arr)>0) && ( ( is_array($arr[0]) && isset($arr[0][$field]) ) || ( is_object($arr[0]) && isset($arr[0]->$field) ) ) ){
            if($case_insensitive==true) $strcmp_fn = "strnatcasecmp";
            else $strcmp_fn = "strnatcmp";

            if($sorting=='SORT_DSC'){
             $fn = create_function('$a,$b', '
              if(is_object($a) && is_object($b)){
               return '.$strcmp_fn.'($a->'.$field.', $b->'.$field.');
              }else if(is_array($a) && is_array($b)){
               return '.$strcmp_fn.'($a["'.$field.'"], $b["'.$field.'"]);
              }else return 0;
             ');

            }else if($sorting=='SORT_ASC'){


             $fn = create_function('$a,$b', '
              if(is_object($a) && is_object($b)){
               return '.$strcmp_fn.'($b->'.$field.', $a->'.$field.');
              }else if(is_array($a) && is_array($b)){
               return '.$strcmp_fn.'($b["'.$field.'"], $a["'.$field.'"]);
              }else return 0;
             ');
            }
            usort($arr, $fn);
            return true;
           }else{
            return false;
           }
          }



    }
   ?

The call:

   $all->sort_by('name',$all->_contacts,'SORT_DSC','false');
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文