[thelist] php: multidimensional arrays; and use array_unique or db index?

Dunstan Orchard dunstan at 1976design.com
Sat Mar 29 03:59:29 CST 2003

>From about 10pm until 2am last night I was desperately trying to understand 
how to extract information from a multidimensional array.

I'm sure it's terribly easy, but I couldn't find a single example that made it 
clear what I should do. I got a little bit frustrated.

Well, really rather angry actually :op

Question 1

In the end I saw the light and came up with this code, but I'd be interested 
to know what the 'proper' way to extract data from a multi-d array is.

$names_array = array();
$i = 0;
while (something)
  //add to array
  $names_array[$i]['postid'] = $postid;
  $names_array[$i]['name'] = $name;


$a = 0;
while(++$a < $i)
  $postid =  $names_array["$a"]['postid'];
  $name =  $names_array["$a"]['name'];
  // set query
  $insert_query = ("INSERT INTO foo SET name = '$name', postid = '$postid'");
  // run query
  $insert_result = mysql_query($insert_query);

Question 2

In my db I have only two fields - 'postid' and 'name' - these are set up to 
work together as unique indexes, so the db won't ever let me insert two rows 
with the same value combination.

Is it more efficient to do an array_unique() sort before attempting to insert 
things into the db, or just let the db reject what it wants?

If I should be doing an array_unique() how do I do that for multidimensional 
arrays? The 'first level' will be unique anyway because it was created using a 
counter, but it's the second level (the 'postid' and 'name') that I'm 
interested in removing duplicates from across the board.

Any ideas?

Thanks very much,

- Dunstan

Dorset, England

More information about the thelist mailing list