开发者

Using an Array as the Key for an Array in PHP

I need to create an association between an Array and a Number; as PHP lacks a Map type, I am trying using an array to achieve this:

$开发者_Python百科rowNumberbyRow = array();
$rowNumberByRow[$rowData] = $rowNumber;

However, when I evaluate the code, I get the following Error:

Warning: Illegal offset type

Just to note, the data stored in the array ($rowData) does not have any 'unique' values that I can use as a key for the $rowNumberByRow Array.

Thanks!

UPDATE: To answer some of my commenters, I am trying to create a lookup table so that my application can find the row number for a given row in O(1) time.


PHP does have a map Class: It's called SplObjectStorage. It can be accessed with exactly the same syntax as a general array is (see Example #2 on the reference).

But to use the class you will have to use the ArrayObject class instead of arrays. It is handled exactly the same way arrays are and you can construct instances from arrays (e.g. $arrayObject = new ArrayObject($array)).

If you don't want to use those classes, you can also just create a function that creates unique hash-strings for your indexes. For example:

function myHash($array){
   return implode('|',$array);
}
$rowNumberByRow[myHash($array)] = $rowNumber;

You will of course have to make sure that your hashes are indeed unique, and I would strongly suggest you use the SplObjectStorage and maybe read a little bit more about the SPL classes of php.


Why not just store the row number in the array? e.g:

$rowData['rowNumber'] = $rowNumber;

You could instead serialize the array, e.g:

$rowNumberByRow[serialize($rowData)] = $rowNumber;

However that's pretty inefficient.


In php you can use only scalar values as an array keys.

If your $rowNumber is unique - then you'd try to use the opposite relation direction. If it is not unique - then you don't have any possible solution I know.


The answer has been alredy given and accepted, but while i was searching for a similar problem, i found this question, and i felt like i should drop a line: when someone wants to use an array with values as keys for another array, it would be useful to use the function array_combine.

If i got the arrays correctly, you could use:

$rowNumberByRow = array_combine($rowData, $rowNumber);

Please take a look at the PHP manual to see some info about permitted values for the keys :)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜