Using an array as a key for an array in PHP

I need to create a relationship between an array and a number; since PHP doesn't have a map type, I'm trying to use 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 note that the data stored in the array ( $rowData ) does not have any β€œunique” values ​​that I can use as a key for the $rowNumberByRow .

Thanks!

UPDATE: To answer some of my commentators, 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.

+6
source share
4 answers

PHP has a map class: it is called SplObjectStorage . Access to it is possible using the same syntax as the general array (see Example # 2 for a link ).

But to use the class you have to use the ArrayObject class instead of arrays. It is processed just like arrays, and you can create instances from arrays (for example, $arrayObject = new ArrayObject($array) ).

If you do not want to use these classes, you can also just create a function that creates unique hash strings for your indexes. For instance:

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

Of course, you have to make sure that your hashes are really unique, and I highly recommend that you use SplObjectStorage and perhaps read a little more about php SPL classes.

+6
source

Why not just keep the line number in the array? eg:

 $rowData['rowNumber'] = $rowNumber; 

Instead, you can serialize the array, for example:

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

However, this is quite inefficient.

+2
source

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

If your $rowNumber is unique, then you will try to use the opposite direction of the relationship. If this is not unique, then you do not have any possible solution that I know.

+1
source

The answer was received and accepted, but while I was looking for a similar problem, I found this question, and it seemed to me that I should refuse the 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 can use:

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

Please take a look at the PHP manual to see information on valid key values ​​:)

0
source

Source: https://habr.com/ru/post/894772/


All Articles