Jump to content

[SOLVED] Unique 'element' in multidimensional array.


Recommended Posts

I'm not sure if this has been asked before, i'm banging my head against the wall trying to figure this out.

 

I gather a name and its corresponding primary key from a database.  I put this into an array, eg. 

 

$data[] = array($check2['Name'], $check2['PKey']);

 

(i need the above code in that format)

 

After i populate the array with the data, I call the sort function to sort the array.  Now I need to find and remove any duplicates but only the first element in the array (the name).

 

For example if I have, lets say this is in the array where: 

 

$data[0] = Apple, 2

$data[1] = Apple, 3

$data[2] = Apple, 19

$data[3] = Banana, 15

$data[4] = Watermelon, 7

 

I want to have only one Apple listed, so my array would then look like this where:

 

$data[0] = Apple, 2 (or 3 or 19 , doesn't matter which one, but only one)

$data[1] = Banana, 15

$data[2] = Watermelon, 7

 

How would that be done?

 

Hope that makes sense.

restructuring your array makes life much simpler

 

<?php
$data[2] = 'Apple';
$data[3] = 'Apple';
$data[19] = 'Apple';
$data[15] = 'Banana';
$data[7] = 'Watermelon';

$udata = array_unique($data);

echo '<pre>', print_r($udata, true), '</pre>';
?>

As he said, restructuring your array would be much more efficient in both readability and speed... that said if you can't change it (already deeply implemented, boss riding you, etc) you could use...

 

function unique_name($array) {
foreach($array as $element) {
	$tmpArray[$element[0]] = $element[1];
}
foreach($tmpArray as $key => $val) {
	$returnArray[] = array($key, $val);
}
return $returnArray;
}

 

This just removes non-unique values by overriding keys and changes it back. As I said, this isn't ideal and you should change your implementation as it would be much faster the way barand posted.

 

edit: changed the function to something a little more efficient.

alternatively

<?php
$data[2] = 'Apple';
$data[3] = 'Apple';
$data[19] = 'Apple';
$data[15] = 'Banana';
$data[7] = 'Watermelon';

$udata = array_unique($data);


// if you need to get to your original structure

$data = array();
foreach ($udata as $k=>$v) $data[] = array ($v, $k);

?>

alternatively

<?php
$data[2] = 'Apple';
$data[3] = 'Apple';
$data[19] = 'Apple';
$data[15] = 'Banana';
$data[7] = 'Watermelon';

$udata = array_unique($data);


// if you need to get to your original structure

$data = array();
foreach ($udata as $k=>$v) $data[] = array ($v, $k);

?>

 

I think this can be done, when I grab the data from the database and populate the array, I could set the code to

$data[($check2['PKey'])] = $check2['Name'];

 

Now i'm curious when I do this how do I get the associated PKey?

 

What i'm doing is populating an HTML SELECT with the VALUE = PKey and the Name as the displayed option.

When the option is changed i need to populate some text boxes with further information about that item from the database, which is why i need the PKey associated with that item.

 

If that makes sense lol.

Now i'm curious when I do this how do I get the associated PKey?

 

most likely you're already using a foreach() function

 

foreach($array as $pkey => $value) {
   echo '<option value="'.$pkey.'">'.$value.'</option>';
}

 

or something along those lines... look for your current implementation and adapt it.

 

if you're using some other odd method you could always use array_keys().

try

<?php
$sql = "SELECT PKey, name FROM mytable";
$res = mysql_query($sql);
$data = array();
while (list($k, $name) = mysql_fetch_row($res))
{
   $data[$k] = $name;
}
$udata = array_unique($data);

echo '<select name="myselect">';
foreach ($udata as $k=>$name)
{
   echo "<option value='$k'> $name</option>" ;
}
echo '</select>';
?>

I'll have to show my code to make this a little easier.

 

$query = mysql_query("SELECT * FROM Table");
		$check = mysql_num_rows($query);
		if ($check != 0)
		{
			print("<BR><SELECT onChange=\"location.href='newtable.php?date=".$setdate."&num=".$datecount."&selected='+(options[selectedIndex].index)+'&key='+(options[selectedIndex].value)\" NAME='Table'>");
			print("<OPTION VALUE=''>*** Select Your Table ***</OPTION>");
			$counter = 0;
			while($check2 = mysql_fetch_array($query))
			{

				if ($counter != 0)
				{
					$found = array_search($check2['Name'], $arrnamekey);
					if ($found == false)
					{
						$arrnamekey[] = array($check2['Name'], $check2['PKey']);
						$arrname[] = $check2['Name'];
						print("<OPTION VALUE='".$check2['PKey']."'>".$check2['Name']."</OPTION>");
					}
				}
				else
				{
					$arrnamekey[] = array($check2['Name'], $check2['PKey']);
					$arrname[] = $check2['Name'];
					print("<OPTION VALUE='".$check2['PKey']."'>".$check2['Name']."</OPTION>");
				}
				$maxcounter = $counter;
				$counter++;


			}
			sort($arrnamekey);
			print("</SELECT>");

		}

 

Inside the while loop I need to put all the data into an array, sort it, and remove the duplicate "NAMES" (as i mentioned before).

 

After that I just need to know how to access the PKey for those names so I can refer to them in the database.

 

BTW, i've been tinkering with this so its a little messy, everything else for the site works fine.  Just need to get this uniqueness and sorting down.

try

<?php
$sql = "SELECT PKey, name FROM mytable";
$res = mysql_query($sql);
$data = array();
while (list($k, $name) = mysql_fetch_row($res))
{
   $data[$k] = $name;
}
$udata = array_unique($data);

echo '<select name="myselect">';
foreach ($udata as $k=>$name)
{
   echo "<option value='$k'> $name</option>" ;
}
echo '</select>';
?>

 

I tried incorporating this into my code and when I run it, it doesn't preserve the PKey, it has it as 0.1.2.3.4...... etc...  It solves the unique problem and I can sort it, but i need to preserve that PKey for the correct Name.

 

Here's my code for it

$query = mysql_query("SELECT PKey, Name FROM Table");
		$check = mysql_num_rows($query);
		$data = array();
		if ($check != 0)
		{
			print("<BR><SELECT onChange=\"location.href='newtable2.php?date=".$setdate."&num=".$datecount."&selected='+(options[selectedIndex].index)+'&key='+(options[selectedIndex].value)\" NAME='Table'>");
			print("<OPTION VALUE=''>*** Select Your Table ***</OPTION>");
			while (list($key, $name) = mysql_fetch_row($query))
			{
				$data[$key] = $name;
			}
		        sort($data);
			$uniquedata = array_unique($data);
			foreach ($uniquedata as $key => $name)
			{
				print("<OPTION VALUE='".$key."'>".$name."</OPTION>");
			}
                                print("</SELECT>");
}

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.