Reputation: 6209
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:
$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.
Upvotes: 9
Views: 5565
Reputation: 255085
In php you can use only scalar values as 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.
Upvotes: 1
Reputation: 70833
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.
Upvotes: 9
Reputation: 4896
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.
Upvotes: 2