Reputation: 6862
I have the following array for tire sizes:
Array
(
[0] => 155
[1] => 70
[2] => 13
)
Array
(
[0] => 155
[1] => 80
[2] => 13
)
Array
(
[0] => 165
[1] => 65
[2] => 14
)
Array
(
[0] => 175
[1] => 65
[2] => 14
)
Array
(
[0] => 175
[1] => 70
[2] => 13
)
Array
(
[0] => 175
[1] => 70
[2] => 14
)
and so on. Now I am creating a drop down so people can select the tire size they are searching for. so here is my PHP code:
include 'database.php';
$result = $mysqli->query('SELECT DISTINCT SKU_SIZE FROM SKU_DATA WHERE SKU_BRANDNAME = "'.$brand.'" ORDER BY SKU_SIZE');
while( $row = $result->fetch_assoc()){
$sku_size = $row['SKU_SIZE'];
$chars = preg_split('/[^\d]/', $sku_size, -1, PREG_SPLIT_NO_EMPTY);
echo "<option>".$chars[0]."</option>";
}
Now that code is just showing the first number in each array, for the very first drop down they select.
Right now it is showing 155, 155, 165, 175, 175 - and what I want it to do is just show the unique values so it would just show 155, 165, 175.
Update: Thanks! I got that part working. One quick question.. the order is not quite right, not sure what I am doing wrong. Here is a preview:
Upvotes: 1
Views: 2103
Reputation: 4967
use this:
while( $row = $result->fetch_assoc()){
$sku_size = $row['SKU_SIZE'];
$chars = preg_split('/[^\d]/', $sku_size, -1, PREG_SPLIT_NO_EMPTY);
$sizes[$chars[0]] = true;
}
ksort($sizes, SORT_NUMERIC);
foreach ($sizes as $size => $tmp){
echo "<option value=\"$size\">$size</option>";
}
Upvotes: 1
Reputation: 23680
You can remove any duplicate unique items from an array using the array_unique() function.
EG:
$arrays = array(1,2,3) + array(1,2,3);
print_r(array_unique($arrays));
// Will print just: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
Upvotes: 2
Reputation: 75599
Make a new array with just the first value
$diameter = array();
foreach ($tires as $tire) {
$diameter[] = $tire[0];
}
Then, use array_unique() to remove the duplicates, or only add them to $diameter if they are not already in there.
Then use that $diameter array to create the dropdown.
This has the advantage that you can also sort the $diameter array.
Upvotes: 1
Reputation: 24661
Create an array and check to see if each value is in the array before outputting it. If it is not in the array, add it in before outputting.
include 'database.php';
$result = $mysqli->query(
'SELECT DISTINCT SKU_SIZE
FROM SKU_DATA WHERE SKU_BRANDNAME = "'.$brand.'"
ORDER BY SKU_SIZE'
);
$seen = array();
while( $row = $result->fetch_assoc()){
$sku_size = $row['SKU_SIZE'];
$chars = preg_split('/[^\d]/', $sku_size, -1, PREG_SPLIT_NO_EMPTY);
if(in_array($chars[0], $seen))
continue;
$seen[] = $chars[0];
echo "<option>".$chars[0]."</option>";
}
Upvotes: 2
Reputation: 4540
Use a temporary array to store the numbers that have been echo
ed then.
Upvotes: 1