开发者

PHP: how to get the same index for the same values in an associative array?

I have an associative array like this :

ID   Val
----------
B     1
C     2
A     1
D     3
E     2
G     4
F     1

I sort the array using asort($array) , so I get :

ID   Val
----------
A     1
B     1
F     1
C     2
E     2
D     3
G     4

I can then find the index of an item with `array_search($id,array_keys($array));

A has an index of 0, B of 1, F of 2 , C of 3, etc. (this is random for items with the same Val, I believe)

But I would like items with the same Val to get the same index, like this :

A,B,F : 0
C,E   : 1
D     : 2
G     : 3

Any idea's ?开发者_如何学Python


This will get all of the unique values, sorted numerically, and return the index of the value related to $array[ $key ]:

array_search( 
    // you're looking for this value
    $array[ $key ], 
    // you only want unique values here (and array_unique applies sort, so 
    // no worries there)
    array_unique( 
        // you don't need the keys here.
        array_values( $arr ), 
        // sorting numerically.
        SORT_NUMERIC ) );

called functions:

  • array_unique
  • array_search
  • array_values

If you're calling the same search multiple times, I would probably wrap this in a class:

class Unique_Value_Query
{
    private $vals;
    private $baseArr;

    public function __construct( array $arr = array() )
    {
       $this->setBaseArray( $arr );
    }

    public function setBaseArray( $ba )
    {
       if( count( $ba ) < 1 ) return;
       $this->baseArray = $ba;
       $this->vals = array_unique( array_values( $ba ) );
    }

    public function getBaseArray(){ return $this->baseArray; }

    public function getKeyIndex( $key )
    {
        return array_search( $this->baseArray[ $key ], $this->vals );
    }

}

$array = array( 'bar' => 0, 'foo' => 1, 'baz' => 1);

$q = new Unique_Value_Query( $array );
echo $q->getKeyIndex( 'foo' ); // 1
echo $q->getKeyIndex( 'bar' ); // 0
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜