Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an Array as the Key for an Array in PHP

Tags:

arrays

php

map

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.

like image 205
JonnyReeves Avatar asked Aug 10 '11 23:08

JonnyReeves


1 Answers

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.

like image 195
Chronial Avatar answered Sep 28 '22 08:09

Chronial