Combine all values and remove duplicates - php

How combine this array and remove duplicate values?
Thank you!
array (size=17)
0 => string 'Black' (length=5)
1 => string 'Blue' (length=4)
2 => string 'Burgundy' (length=8)
3 => string 'Glow' (length=4)
4 => string 'Granite' (length=7)
5 => string 'Green' (length=5)
6 => string 'Lime' (length=4)
7 => string 'Natural' (length=7)
8 => string 'Orange' (length=6)
9 => string 'Pink' (length=4)
10 => string 'Purple' (length=6)
11 => string 'Red' (length=3)
12 => string 'Silver' (length=6)
13 => string 'Teal' (length=4)
14 => string 'Violet' (length=6)
15 => string 'White' (length=5)
16 => string 'Yellow' (length=6)
Thank you, your code worked perfectly.
I'm still missing something because I don't get what I want.
The values (color names) are in the select form, but when a value other than 'Filter by Color' is selected, the 'id' is what pass instead of the 'text'. To make things easy, here is the complete code.
Thank you.
$Sql_product_colors = ("SELECT COUNT(p.products_id) AS id, pia.product_filter_colors FROM products p LEFT JOIN products_imprint_areas pia on p.products_id = pia.products_id
WHERE p.products_id > '1'
AND pia.product_filter_colors IS NOT NULL
GROUP BY product_filter_colors
ORDER BY product_filter_colors asc");
$sort_list_colors = array();
$product_filter_colors = tep_db_query($Sql_product_colors) or die(mysql_error());
while ($row = mysql_fetch_array($product_filter_colors)) {
$arrColor = explode(',', $row[1]);
$arrColors=array_filter(array_map('trim', $arrColor));
$sort_list_color = array_merge($sort_list_colors,$arrColors);
$sort_list_colors = array_unique($sort_list_color);
sort($sort_list_colors);
}
$sort_list_colors[0] ='Filter by Color';
$sort_list_colors[] =' '.$row[$sort_list_colors].' (' .$sort_list_colors['count'].')';
if(count($sort_list_colors)>0)
{
foreach($sort_list_colors as $id=>$text) {
$sort_range_colors[] = array('id' => $id, 'text' => $text);
}
}
// -------------------------------------- Select form
echo '<td align="center" width="25%" valign="middle"><div class="styled-select">' . tep_draw_form('colors_sort', htmlentities($_SERVER['PHP_SELF']), 'get') . '';
echo tep_draw_pull_down_menu('colors_sort', $sort_range_colors, (isset($HTTP_GET_VARS['colors_sort']) ? $HTTP_GET_VARS['colors_sort'] : ''), 'onchange="this.form.submit()"');
echo '</form></div></td>';
This is the function tep_draw_pull_down_menu. Thank you.
function tep_draw_pull_down_menu($name, $values, $default = '', $parameters = '', $required = false) {
$field = '<select name="' . tep_output_string($name) . '"';
if (tep_not_null($parameters)) $field .= ' ' . $parameters;
$field .= '>';
if (empty($default) && isset($GLOBALS[$name])) $default = stripslashes($GLOBALS[$name]);
for ($i=0, $n=sizeof($values); $i<$n; $i++) {
$field .= '<option value="' . tep_output_string($values[$i]['id']) . '"';
if ($default == $values[$i]['id']) {
$field .= ' SELECTED';
}
$field .= '>' . tep_output_string($values[$i]['text'], array('"' => '"', '\'' => ''', '<' => '<', '>' => '>')) . '</option>';
}
$field .= '</select>';
if ($required == true) $field .= TEXT_FIELD_REQUIRED;
return $field;
}

Use array_merge then array_unique,
$colors = array();
while ($row = mysql_fetch_array($filter_colors)) {
$arrColors = explode(',', $row[1]);
$colors = array_merge($colors,$arrColors);
}
$colors = array_unique($colors);
Warning: Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

Related

How to sort by two values then a field by ASC in an array using usort() in PHP?

I have parsed three different text files:
space.txt
Kournikova Anna F F 6-3-1975 Red
Hingis Martina M F 4-2-1979 Green
Seles Monica H F 12-2-197
comma.txt
Abercrombie, Neil, Male, Tan, 2/13/1943
Bishop, Timothy, Male, Yellow, 4/23/1967
Kelly, Sue, Female, Pink, 7/12/1959
pipe.txt
Smith | Steve | D | M | Red | 3-3-1985
Bonk | Radek | S | M | Green | 6-3-1975
Bouillon | Francis | G | M | Blue | 6-3-1975
I used the following code to parse all files into one array .............
<?php
$space_txt = './data/input/space.txt';
$comma_txt = './data/input/comma.txt';
$pipe_txt = './data/input/pipe.txt';
$parsed_space_data = file_get_contents($space_txt);
$parsed_comma_data = file_get_contents($comma_txt);
$parsed_pipe_data = file_get_contents($pipe_txt);
$space_array = myExpldeLoopFunc("space"," ", $parsed_space_data);
$comma_array = myExpldeLoopFunc("comma",",", $parsed_comma_data);
$pipe_array = myExpldeLoopFunc("pipe"," | ", $parsed_pipe_data);
$finalArray = array_merge($space_array, $comma_array, $pipe_array);
function changeGender($gender) {
if($gender === 'F') {
return str_replace('F', 'Female', $gender);
}
elseif($gender === 'M') {
return str_replace('M', 'Male', $gender);
}
}
function normalizeDate($date) {
return str_replace('-', '/', $date);
}
function myExpldeLoopFunc($name, $sep, $data) {
$parsedData = explode("\r", $data);
$arr = [];
foreach ($parsedData as $data) {
$data_arr = explode($sep, $data);
if($name == 'space'){
$arr[] = [
"last_name" => $data_arr[0],
"first_name" => $data_arr[1],
// "middle_initial" => $data_arr[2],
"gender" => changeGender($data_arr[3]),
"date_of_birth" => normalizeDate($data_arr[4]),
"favorite_color" => $data_arr[5]
];
}
elseif($name == 'comma') {
$arr[] = [
"last_name" => $data_arr[0],
"first_name" => $data_arr[1],
"gender" => $data_arr[2],
"date_of_birth" => normalizeDate($data_arr[4]),
"favorite_color" => $data_arr[3]
];
}
elseif ($name == 'pipe') {
$arr[] = [
"last_name" => $data_arr[0],
"first_name" => $data_arr[1],
// "middle_initial" => $data_arr[2],
"gender" => changeGender($data_arr[3]),
"date_of_birth" => normalizeDate($data_arr[5]),
"favorite_color" => $data_arr[4]
];
}
}
return $arr;
}
for ($i=0; $i < count($finalArray); $i++) {
foreach ($finalArray as $key => $row) {
$gender[$key] = $row['gender'];
$last_name[$key] = $row['last_name'];
}
array_multisort($gender, SORT_ASC, $last_name, SORT_ASC, $finalArray);
echo join(' ', $finalArray[$i]) . '<br>';
}
var_dump($finalArray);
?>
Now I have the following array ...........
array (size=9)
0 =>
array (size=5)
'last_name' => string 'Kournikova' (length=10)
'first_name' => string 'Anna' (length=4)
'gender' => string 'Female' (length=6)
'date_of_birth' => string '6/3/1975' (length=8)
'favorite_color' => string 'Red' (length=3)
1 =>
array (size=5)
'last_name' => string '
Hingis' (length=7)
'first_name' => string 'Martina' (length=7)
'gender' => string 'Female' (length=6)
'date_of_birth' => string '4/2/1979' (length=8)
'favorite_color' => string 'Green' (length=5)
2 =>
array (size=5)
'last_name' => string '
Seles' (length=6)
'first_name' => string 'Monica' (length=6)
'gender' => string 'Female' (length=6)
'date_of_birth' => string '12/2/1973' (length=9)
'favorite_color' => string 'Black' (length=5)
3 =>
array (size=5)
'last_name' => string 'Abercrombie' (length=11)
'first_name' => string ' Neil' (length=5)
'gender' => string ' Male' (length=5)
'date_of_birth' => string ' 2/13/1943' (length=10)
'favorite_color' => string ' Tan' (length=4)
4 =>
array (size=5)
'last_name' => string '
Bishop' (length=7)
'first_name' => string ' Timothy' (length=8)
'gender' => string ' Male' (length=5)
'date_of_birth' => string ' 4/23/1967' (length=10)
'favorite_color' => string ' Yellow' (length=7)
5 =>
array (size=5)
'last_name' => string '
Kelly' (length=6)
'first_name' => string ' Sue' (length=4)
'gender' => string ' Female' (length=7)
'date_of_birth' => string ' 7/12/1959' (length=10)
'favorite_color' => string ' Pink' (length=5)
6 =>
array (size=5)
'last_name' => string 'Smith' (length=5)
'first_name' => string 'Steve' (length=5)
'gender' => string 'Male' (length=4)
'date_of_birth' => string '3/3/1985' (length=8)
'favorite_color' => string 'Red' (length=3)
7 =>
array (size=5)
'last_name' => string '
Bonk' (length=5)
'first_name' => string 'Radek' (length=5)
'gender' => string 'Male' (length=4)
'date_of_birth' => string '6/3/1975' (length=8)
'favorite_color' => string 'Green' (length=5)
8 =>
array (size=5)
'last_name' => string '
Bouillon' (length=9)
'first_name' => string 'Francis' (length=7)
'gender' => string 'Male' (length=4)
'date_of_birth' => string '6/3/1975' (length=8)
'favorite_color' => string '
Blue' (length=4)
So Far the output is ........
Kelly Sue Female 7/12/1959 Pink
Bishop Timothy Male 4/23/1967 Yellow
Abercrombie Neil Male 2/13/1943 Tan
Hingis Martina Female 4/2/1979 Green
Seles Monica Female 12/2/1973 Black
Kournikova Anna Female 6/3/1975 Red
Bonk Radek Male 6/3/1975 Green
Bouillon Francis Male 6/3/1975 Blue
Smith Steve Male 3/3/1985 Red
I want to sort the array by Females then Males, then by last_name asc ........
Hingis Martina Female 4/2/1979 Green
Kelly Sue Female 7/12/1959 Pink
Kournikova Anna Female 6/3/1975 Red
Seles Monica Female 12/2/1973 Black
Abercrombie Neil Male 2/13/1943 Tan
Bishop Timothy Male 4/23/1967 Yellow
Bonk Radek Male 6/3/1975 Green
Bouillon Francis Male 6/3/1975 Blue
Smith Steve Male 3/3/1985 Red
I also tried ......
function sortBy($field, &$array, $direction = 'asc') {
usort($array, create_function('
$a, $b', ' $a = $a["' . $field . '"];
$b = $b["' . $field . '"];
if ($a == $b) {
return 0;
}
return ($a ' . ($direction == 'desc' ? '>' : '<') .' $b) ? -1 : 1; '));
return true;
}
for ($i=0; $i < count($finalArray); $i++) {
sortBy('gender', $finalArray);
sortBy('last_name', $finalArray);
echo join(' ', $finalArray[$i]) . '<br>';
}
I have tried array_multisort(), usort(), sort(), asort(), and I still couldn't produce the results I wanted. What solution can be used to produce the outcome?
Ok, I'll give an example, with two criteria, but it's untested on your data. So the compare() function below receives two arrays to compare. How to do that? Each array, in the example, contains two numbers, first we sort on the number with key = 0 and then on the number with key = 1. Your keys are, of course, different.
function compare($array1,$array2)
{
// numbers at key 0 are equal
if ($array1[0] == $array2[0])
{
// so we look at key 1.
if ($array1[1] == $array2[1]) return 0;
return ($array1[1] < $array2[1]) ? -1 : 1;
}
return ($array1[0] < $array2[0]) ? -1 : 1;
}
$a = [[1,2],[3,4],[5,4],[4,2],[1,8]];
usort($a,'compare');
foreach ($a as $key => $value)
{
echo "<pre>$key: ".print_r($value,TRUE)."\n</pre>";
}
All you need to do is to adapt this to your case.
This sorts on two values in an array, both, as you would call it, ascending. Just change the < to > if you want one of them in decending order. The keys used here are 0 and 1, your keys are like gender and last_name.
Some values cannot be compared with the < comparison operator, so you would need to use something else. In case of the last_name you might want to use strcasecmp().
The main issues in your code:
You split by \r: it is better to split by \n which works on all platforms. But since a line-feed can be \r\n, you need to remove that other character as well. This you can do with trim(). So I would suggest to apply trim() to all values.
The changeGender function looks weird. You can do all that with: return $gender === 'F' ? 'Female' : 'Male'.
You might also want to skip empty lines in your input.
You do your sorting in a loop on your array, that is wrong. That outer loop should be removed. If you need it for listing the data, then move the sorting out of it.
The corrected code (and also nicely indented) follows with my comments marked as //**:
$space_txt = './data/input/space.txt';
$comma_txt = './data/input/comma.txt';
$pipe_txt = './data/input/pipe.txt';
$parsed_space_data = file_get_contents($space_txt);
$parsed_comma_data = file_get_contents($comma_txt);
$parsed_pipe_data = file_get_contents($pipe_txt);
$space_array = myExpldeLoopFunc("space", " ", $parsed_space_data);
$comma_array = myExpldeLoopFunc("comma", ",", $parsed_comma_data);
$pipe_array = myExpldeLoopFunc("pipe", " | ", $parsed_pipe_data);
$finalArray = array_merge($space_array, $comma_array, $pipe_array);
function changeGender($gender) {
return $gender === 'F' ? 'Female' : 'Male'; //** This is more straightforward
}
function normalizeDate($date) {
return str_replace('-', '/', $date);
}
function myExpldeLoopFunc($name, $sep, $data) {
$parsedData = explode("\n", $data); //** use "\n" instead of "\r"
$arr = [];
foreach ($parsedData as $data) {
if ($data === "") continue; //** skip empty lines
$data_arr = explode($sep, $data);
if($name == 'space'){
$arr[] = [
"last_name" => trim($data_arr[0]), //** trim all elements (also removes "\r")
"first_name" => trim($data_arr[1]),
// "middle_initial" => trim($data_arr[2]),
"gender" => changeGender(trim($data_arr[3])),
"date_of_birth" => normalizeDate(trim($data_arr[4])),
"favorite_color" => trim($data_arr[5])
];
} elseif($name == 'comma') {
$arr[] = [
"last_name" => trim($data_arr[0]),
"first_name" => trim($data_arr[1]),
"gender" => trim($data_arr[2]),
"date_of_birth" => normalizeDate(trim($data_arr[4])),
"favorite_color" => trim($data_arr[3])
];
} elseif ($name == 'pipe') {
$arr[] = [
"last_name" => trim($data_arr[0]),
"first_name" => trim($data_arr[1]),
// "middle_initial" => trim($data_arr[2]),
"gender" => changeGender(trim($data_arr[3])),
"date_of_birth" => normalizeDate(trim($data_arr[5])),
"favorite_color" => trim($data_arr[4])
];
}
}
return $arr;
}
//** Removed the bad for-loop that appeared here.
foreach ($finalArray as $key => $row) {
$gender[$key] = $row['gender'];
$last_name[$key] = $row['last_name'];
}
array_multisort($gender, SORT_ASC, $last_name, SORT_ASC, $finalArray);
//** Output in a loop, but leave the above sorting out of it
foreach ($finalArray as $row) {
echo join(' ', $row) . "<br>\n";
}
print_r($finalArray);
See it run on eval.in which uses the sample data you provided.
The order is as desired.

For each only returns first iteration

I'm trying to run through an object. I'm having an issue with my initial for each only running through the first iteration. So everything is great, but I'm only getting one iteration while their are 3. Any ideas why this may be happening?
<?php
global $wpdb;
/*Begin*/
$itemsTable = $wpdb->prefix . "HFW_portfolio_items";
$catTable = $wpdb->prefix . "HFW_portfolio_categories";
$tagTable = $wpdb->prefix . "HFW_portfolio_tags";
$rowsItemA = $wpdb->get_results("SELECT * FROM"." $itemsTable"."", ARRAY_A);
exit(var_dump($rowsItemA));
$numItems = count($rowsItem);
$i = 0;
//exit(var_dump($rowsItem));
foreach ($rowsItemA as $rowsItem ){
//$id = $rowsItem[id];
$port_item = "";
$id = stripslashes ($rowsItem[id]);
//exit(var_dump($id));
$portfolio_category = stripslashes ($rowsItem[portfolio_category]);
$sql = "SELECT * FROM"." $catTable"." WHERE id="."$portfolio_category"." LIMIT 1";
$catNameDB = $wpdb->get_results($sql);
/*from Above Select for CATEGORY*/
foreach ($catNameDB as $catNameDBs ){
$portfolio_category = stripslashes ($catNameDBs->cat_name);
}/**/
$portfolio_name = stripslashes ($rowsItem[portfolio_name]);
$portfolio_active = stripslashes ($rowsItem[portfolio_active]);
$portfolio_tags = stripslashes ($rowsItem[portfolio_tags]);
$portfolio_main_image = stripslashes ($rowsItem[main_image]);
$portfolio_desc = stripslashes ($rowsItem[portfolio_desc]);
$image_2 = stripslashes ($rowsItem[image_2]);
$image_3 = stripslashes ($rowsItem[image_3]);
$portfolio_website = stripslashes ($rowsItem[portfolio_website]);
//exit(var_dump($image_2,$image_3));
if($image_2 !== '' || $image_2 = null)
{
$image_2 = ",'".$image_2."',";
}
else
{
$image_2 = '';
}
if($image_3 !== '' || $image_3 = null)
{
$image_3 = ",'".$image_3."'";
}
else
{
$image_3 = '';
}
$port_item .= "
{
'title' : '".$portfolio_name."',
'description' : '".$portfolio_desc."',
'thumbnail' : ['".$portfolio_main_image."' ".$image_2." ".$image_3."],
'large' : ['".$portfolio_main_image."' ".$image_2." ".$image_3."],
'tags' : ['".$portfolio_category."']
}
";
if(++$i === $numItems) {
$port_item .= "";
}
else
$port_item .=",";
//exit(var_dump($i,$numItems));
}
?>
exit(var_dump($rowsItemA));
array (size=3)
0 =>
array (size=10)
'id' => string '9' (length=1)
'portfolio_name' => string 'Da' (length=26)
'main_image' => string 'elicate-dashley-1.png' (length=101)
'image_2' => string 'n-and-mn.png' (length=107)
'image_3' => string '' (length=0)
'portfolio_active' => string '0' (length=1)
'portfolio_category' => string '1' (length=1)
'portfolio_desc' => string 'test1' (length=246)
'portfolio_tags' => string '["1","2","3","4","5","6","10"]' (length=30)
'portfolio_website' => string 'http://www.test.com/' (length=26)
1 =>
array (size=10)
'id' => string '10' (length=2)
'portfolio_name' => string 'Sage' (length=29)
'main_image' => string 'purs-er.png' (length=99)
'image_2' => string '' (length=0)
'image_3' => string '' (length=0)
'portfolio_active' => string '0' (length=1)
'portfolio_category' => string '1' (length=1)
'portfolio_desc' => string 'test 2' (length=249)
'portfolio_tags' => string '["1","2","5","6","9","10"]' (length=26)
'portfolio_website' => string 'http://www.test.com/test' (length=27)
2 =>
array (size=10)
'id' => string '11' (length=2)
'portfolio_name' => string 'Scap' (length=20)
'main_image' => string 's-day-cap.png' (length=93)
'image_2' => string '' (length=0)
'image_3' => string '' (length=0)
'portfolio_active' => string '0' (length=1)
'portfolio_category' => string '1' (length=1)
'portfolio_desc' => string 'test 3' (length=155)
'portfolio_tags' => string '["1","2","5","6","9","10"]' (length=26)
'portfolio_website' => string 'http://www.test.com/test/test' (length=44)
This is because, you have made $port_item = "" in brginning of the loop.
foreach ($rowsItemA as $rowsItem ){
$port_item = "";// declaring as null here(remove this.)
So in every loop your value is reinitialized, and you are getting only 1 element(last element of your array)

Iterate through arrays and input into database

I have a form with capturing data and posting in an array named "table" so the tables, columns and tuples are linked.
I am now trying to iterate through them and seperate them into there individual strings,
"$table" = name
"$columns" = columns
"$columnData" = data
When i do a var_dump on the data, it looks like:-
array (size=2)
0 =>
array (size=3)
'name' => string 'quote' (length=5)
'columns' =>
array (size=3)
0 => string 'qid' (length=3)
1 => string 'item' (length=4)
2 => string 'price' (length=5)
'data' =>
array (size=3)
0 => string '1' (length=1)
1 => string 'ball' (length=4)
2 => string '200' (length=3)
1 =>
array (size=3)
'name' => string 'rfq' (length=3)
'columns' =>
array (size=2)
0 => string 'id' (length=2)
1 => string 'item' (length=4)
'data' =>
array (size=2)
0 => string '1' (length=1)
1 => string 'batt' (length=4)
Which looks in the correct format, although when i try to insert into the database it does not insert, there is something about the $columns variable in the insert statement that does not work.
Although I am unsure if i am iterating through the data correctly.
$AllData = $_POST["table"];
// var_dump($AllData)
foreach ($AllData as $sigleData) {
$table = $sigleData['name'];
$columns = implode(" ", $sigleData['columns']);
$columnData = implode(" ", $sigleData['data']);
$sqlQuery = "INSERT INTO " . $table . " ( " . $columns . ") VALUES( '" . $columnData . "')";
if ($dbConnectionT->query($sqlQuery) == TRUE) {
echo "database updated";
echo "</br>";
}
}
So table quote has columns qid, item and price.
with values 1, ball and 200 which i am trying to insert correctly into.
Please note, I understand the database violations here, but trying to get the programming example working,
If the previous page is required, please comment. Thanks in advance.
Try with -
foreach ($AllData as $sigleData) {
$table = $sigleData['name'];
$columns = implode(", ", $sigleData['columns']);
$columnData = implode(" ',' ", $sigleData['data']);
$sqlQuery = "INSERT INTO " . $table . " ( " . $columns . ") VALUES( '" . $columnData . "')";
if ($dbConnectionT->query($sqlQuery) == TRUE) {
echo "database updated";
echo "</br>";
}
}
In your insert query you are building VALUE part with a single ' for both values... Just change the implode param with "', '"

Store value in multi-dimentional array on unique key

How do I display the following using the array shown below?
Pastors
key=>0, member_id, member_name
Deacons
key=>1, member_id, member_name
key=>2, member_id, member_name
Here is the array.
array (size=3)
0 =>
array (size=4)
'category_name' => string 'Pastors' (length=7)
'member_id' => string '3' (length=1)
'member_name' => string 'Tiny Marshall' (length=13)
'member_email' => string 'jconley#nowhere.com' (length=19)
1 =>
array (size=4)
'category_name' => string 'Deacons' (length=7)
'member_id' => string '1' (length=1)
'member_name' => string 'Jeremiah Conley' (length=15)
'member_email' => string 'jconley#nowhere.com' (length=19)
2 =>
array (size=4)
'category_name' => string 'Deacons' (length=7)
'member_id' => string '2' (length=1)
'member_name' => string 'Marcy Conley' (length=12)
'member_email' => string 'jconley#nowhere.com' (length=19)
Here is the code that I used to build the array:
while( $row = mysql_fetch_assoc( $result ) )
{
$staff[$i] = array
(
'category_name' => $row['category_name'],
'member_id' => $row['member_id'],
'member_name' => $row['member_name'],
'member_email' => $row['member_email'],
);
$i++;
}
This is the final solution:
$category_name = array();
foreach ($staff as $member) {
if (!in_array( $member['category_name'], $category_name ))
{
echo '<h1>' . $member['category_name'] . '</h1>';
$category_name[] = $member['category_name'];
}
echo $member['member_id'] . ', ' . $member['member_name'] . '<br />';
}
Use foreach to loop over your $staff array.
$pastors = array();
$deacons = array();
foreach ($staff as $member) {
if ($member['category_name'] == 'Pastors') {
$pastors[] = $member['member_id'] . ', ' . $member['member_name'];
} else if ($member['category_name'] == 'Deacons') {
$deacons[] = $member['member_id'] . ', ' . $member['member_name'];
}
}
documentation

How to loop through arrays of arrays in PHP

I'd like to take an array with this structure:
array
'Alabama' =>
array
0 =>
array
'id' => string '11' (length=2)
'region_name' => string 'Alabama' (length=7)
'city' => string 'Birmingham' (length=10)
1 =>
array
'id' => string '12' (length=2)
'region_name' => string 'Alabama' (length=7)
'city' => string 'Huntsville' (length=10)
2 =>
array
'id' => string '13' (length=2)
'region_name' => string 'Alabama' (length=7)
'city' => string 'Mobile' (length=6)
3 =>
array
'id' => string '14' (length=2)
'region_name' => string 'Alabama' (length=7)
'city' => string 'Montgomery' (length=10)
'Alaska' =>
array
0 =>
array
'id' => string '15' (length=2)
'region_name' => string 'Alaska' (length=6)
'city' => string 'Anchorage' (length=9)
And create unordered lists in html, like so:
<ul id="A">
<li class="state">Alabama</li>
<li>Birmingham</li>
<li>Huntsville</li>
<li>Mobile</li>
<li>Montgomery</li>
<li class="state">Alaska</li>
<li>Anchorage</li>
</ul>
<ul id="C">
<li class="state">California</li>
<li>Bakersfield</li>
<li>Fresno</li>
<li>Los Angeles</li>
</ul>
<ul id="D">
<li class="state">DC</li>
<li>Washington</li>
</ul>
The idea is an alphabetically ordered and grouped series of unordered lists, which I can show and hide easily using javascript. That part is easy... This part, I'm lost.
I've tried a sort of nested foreach loop, but the framework I'm using refused to do it citing OutputEscaper errors, which I believe made sense - I really am not sure how to do this properly.
I'd appreciate any help!
edit: Here's how the array is initially formatted:
$this->cityGroups = array();
foreach($this->USCities as $city)
{
$this->cityGroups[$city['region_name']][] = $city;
}
This is simple and it doesn't need a framework. If you data was formatted as I mentioned in my comment...
$data = array('Alabama' => array('Birmingham', 'Huntsville', 'Mobile', 'Montgomery'),
'Alaska' => array('Anchorage'));
ksort($data);
$formatted = array();
foreach($data as $state => $cities) {
$formatted[$state{0}][$state] = $cities;
}
foreach($formatted as $letter => $states) {
echo '<ul id="'.$letter.'">';
foreach($states as $state => $cities) {
sort($cities);
echo '<li class="state">'.$state.'</li>'
foreach($cities as $city) {
echo '<li>'.$city.'</li>';
}
}
echo '</ul>';
}
This solution should achieve what you're looking for:
$lastLetter = "A";
print( '<ul id="A">' );
foreach( $myArray as $key => $array ){
if( strtoupper( substr( $key, 0, 1 ) ) != $lastLetter ){
print( '</ul>' );
$lastLetter = strtoupper( substr( $key, 0, 1 ) );
print( '<ul id="' . $lastLetter . '">' );
}
print( '<li class="state">' . $key . '</li>' );
foreach( $array as $subArr ){
print( '<li>' . $subArr['city'] . '</li>' );
}
}
print( '</ul>' );
If you need an explanation on any specific part, please let me know.
Alternate Solution, in the event your starting letter is variable (may or may not be A)
Change:
$lastLetter = "A";
print( '<ul id="A">' );
to:
$temp = array_keys( $myArray );
$lastLetter = strtoupper( substr( $temp[0], 0, 1 ) );
print( '<ul id="' . $lastLetter . '">' );

Categories