Show Store name by group in Alphabetical - php - php

i want to show stores name in alphabetically format. I have a store table where I am storing all details about a store including its name, logo, discription etc. I want the name will appear as a alphabetical group wise. Such as shown in example. and also show stores by clicking on [A] [B] [C] .... [Z]
A
--> 'Amazon'
--> 'Apple'
B
--> 'Ba...'
--> 'Be...'
<?php
$temp = array(); // would also generate a dynamic array
$result = mysql_query("SELECT LEFT(`name_en-GB`, 1 ) AS FirstLetter, `name_en-GB` FROM `store` ORDER BY FirstLetter, `name_en-GB`");
while ($row = mysql_fetch_array($result)) {
$temp[$row['FirstLetter']][] = $row['name_en-GB'];
}
Output:
Array
(
[1] => Array
(
[0] => 100bestbuy.com
)
[A] => Array
(
[0] => Adlabsimagica
[1] => Airasiago
[2] => Airtel
)
[B] => Array
(
[0] => Babyhugz
[1] => Babyoye
[2] => Bagskart
[3] => Basicslife
[4] => Bata
)
[C] => Array
(
[0] => Clifton
[1] => Coke2Home
[2] => Condompoint
[3] => Croma
)
[D] => Array
(
[0] => Dabur
[1] => Dealofthedayindia.com
[2] => Dhamaal
[3] => Dominos
)

You can use another array to save position where you are.
Something like this:
<?php
$temp = array(); // would also generate a dynamic array
$position = array();
foreach (range('0', '9') as $i) {
$position [$i] = 0;
}
foreach (range('a', 'z') as $i) {
$position [$i] = 0;
}
$result = mysql_query("SELECT LEFT(`name_en-GB`, 1 ) AS FirstLetter, `name_en-GB` FROM `store` ORDER BY FirstLetter, `name_en-GB`");
while ($row = mysql_fetch_array($result)) {
$pos = $position[$row['FirstLetter']];
$position ['FirstLetter'] ++;
$temp[$row['FirstLetter']][$pos] = $row['name_en-GB'];
}
?>
Now you have an array with positions in subarray.
Should be working, just be carefully to have all firstletters uppercase/downcase or verifiy before

Related

PHP - Array does not turn into two-dimensional array

I need to make my array better.
I am getting data from database and i have milestones and milestone_parts. i want two-dimensional array. I need data of milestones in the first dimension and milestone_parts in the second dimension.
With this code:
$query = "
SELECT
a.id AS `milestone_id`,
a.titel AS `milestone_titel`,
a.client AS `client`,
a.verkocht_id AS `milestone_verkocht_id`,
b.id AS `milestonefase_id`,
b.titel AS `milestonefase_titel`,
b.milestone_id AS `milestonefase_milestone_id`,
b.omschrijving AS `milestonefase_omschrijving`
FROM `milestones` a
INNER JOIN `milestone_parts` b ON a.id=b.milestone_id
WHERE a.verkocht_id = '99'
";
$result= $db->query($dbh, $query);
while ($row = $db->fetchassoc($result))
{
$stone = array($row['milestone_verkocht_id'], $row['milestone_id'], $row['milestone_titel'], $row['client']);
$fase = array($row['milestonefase_milestone_id'],$row['milestonefase_id'],$row['milestonefase_titel']);
$stone[] = $fase;
echo '<pre>'; print_r($stone); echo '</pre>';
}
I get this as result
Array
(
[0] => 99
[1] => 6
[2] => string
[3] => string
[4] => Array
(
[0] => 6
[1] => 10
[2] => string
)
)
Array
(
[0] => 99
[1] => 6
[2] => string
[3] => string
[4] => Array
(
[0] => 6
[1] => 11
[2] => string
)
)
but I need (with names) this:
Array
(
[milestone_verkocht_id] => 99 // This is project id
[milestone_id] => 6
[milestone_title] => string
[client] => string
[10] => Array
(
[milestonefase_milestone_id] => 6
[milestonefase_id] => 10
[milestone_title] => string
)
[11] => Array
(
[milestonefase_milestone_id] => 6
[milestonefase_id] => 11
[milestone_title] => string
)
[12] => Array
(
[milestonefase_milestone_id] => 6
[milestonefase_id] => 12
[milestone_title] => string
)
)
Can you help me or do you have a solution? Help me please!
you can cycle each field returned by the query, checking the field name and making new arrays
$stones = array();
while ($row = $db->fetchassoc($result)) {
$fase = array();
$stone = array('milestones' => array());
foreach ($row as $k => $v) {
if (strpos($k, 'milestonefase_') === 0) {
$fase[$k] = $v;
} else {
$stone[$k] = $v;
}
}
if(!isset($stones[$stone['milestone_id']])) {
$stones[$stone['milestone_id']] = $stone;
}
$stones[$stone['milestone_id']]['milestones'][$fase['milestonefase_id']] = $fase;
}
echo '<pre>'.print_r($stones, true).'</pre>';
Edit
made some changes in order to match the request. Now we use $stones to store the information we already have on a milestone, adding to it the different "$fase" returned from the query
Probably a more clean way is to retrieve all the information with two different queries one for milestones and the other for the fases
Edit2
Added a sub-array for the milestone fases

How to print out Multi-Dimensional Arrays in php

Consider the array is:
Array
(
[Page-1] => Array
(
[0] => Array
(
[0] => Cat-1
[1] => Item-1
)
)
[Page-2] => Array
(
[0] => Array
(
[0] => Cat-2
[1] => Item-2
)
[1] => Array
(
[0] => Cat-3
[1] => Item-3
)
[2] => Array
(
[0] => Cat-4
[1] => Item-4
)
)
[Page-3] => Array
(
[0] => Array
(
[0] => Cat-5
[1] => Item-5
)
)
[Page-4] => Array
(
[0] => Array
(
[0] => Cat-6
[1] => Item-6
)
)
[Page-5] => Array
(
[0] => Array
(
[0] => Cat-7
[1] => Item-7
)
[1] => Array
(
[0] => Cat-9
[1] => Item-9
)
)
[Page-6] => Array
(
[0] => Array
(
[0] => Cat-8
[1] => Item-8
)
)
)
Where, the first keys [Page-x] from array will be Main-Links in the navigation menu.
Some of the main links may have Sub-Links, some not.
Sub-links are the values of the key [0] of the 3rd sub-array.
And finally the URL for each and every link will be the value of key [1] of the 3rd sub-Array.
Only Pages that have more than one category will show its categories as sub-links
The navigation bar i would like to have:
1. Page-1
2. Page-2
Cat-2
Cat-3
Cat-4
3. Page-3
4. Page-4
5. Page-5
Cat-7
Cat-9
6. Page-6
the PHP code
$records = $p->main_links();
foreach ($records as $key => $value) {
$return[$value['page']][] = array($value['child'], $value['item']);
}
foreach ($return as $key2 => $value2) {
$count = 0;
/* Select a specific value within the Array */
$main_links = $value2[$count][1]; /* URL of the main Pages */
$count = count($return[$key2]);
if($count > 1) {
foreach ($value2 as $key3 => $value3)
{
$link_name = $value3[0]; /* Child Link Names */
$link_url = $value3[1]; /* URL of Child Links */
/* addedd htmlspecialchars() function to $variables that will be echoed into HTML. It provides some XSS protection */
$cat_link .= '<li>'.htmlspecialchars($link_name).'</li>';
}
$result .= '
<li '.htmlspecialchars($li_class).'><span>'.htmlspecialchars($key2).'</span>
<ul>
'.$cat_link.'
</ul>
</li>';
}else {
$result .= '
<li><span>'.htmlspecialchars($key2).'</span></li>';
}
}
Unfortunately i can't get it work... the output is not what i am expecting :(
current Output (wrong one):
1. Page-1
2. Page-2
Cat-2
Cat-3
Cat-4
3. Page-3
4. Page-4
5. Page-5
Cat-2
Cat-3
Cat-4
Cat-7
Cat-9
6. Page-6
Any help would be appreciated!
Your current code is close to working. This line will always produce a count of 1.
$count = count($value);
What you're looking for there, I believe, is:
$count = count($return[$key]);
I've found another way around which is way better than the one i was trying to do. This solved my case.
http://wizardinternetsolutions.com/articles/web-programming/single-query-dynamic-multi-level-menu
Thank you for your support!

Building a recursive function to create a multidimensional array

I think what I want is a recursive function, but please let me know if there's another way to achieve what I want to do! I'm not sure I'm going to explain this very well, so please let me know if you need further clarification.
I've got a function, findSeed() which takes an id and returns an array that contains information about the "seed":
function findSeeds($id) {
global $wpdb;
$query = "SELECT * FROM seedTable WHERE id = " . $id;
$seed = $wpdb->get_row($query, ARRAY_A);
return $seed;
}
It returns the following array:
Array
(
[id] => 9
[name] => Sign
[seed1] => 4
[seed2] => 3
)
Where seed 1 and seed 2 are the ids of the seeds needed to create it. I'm looking to make a function that will create a multidimensional array, in the following format, where the first part of the array contains the first "seed", the next contains the two seeds contained in the first, the next contains the two seeds contained in each of those, and so on:
Array
(
[1] => Array
(
[0] => Stripey Wallpaper
)
[2] => Array
(
[0] => Green Block
[1] => Aqua Block
)
[3] => Array
(
[0] => Bricks
[1] => Grass
[2] => Bricks
[3] => Glass Pane
)
[4] => Array
(
[0] => Rock
[1] => Grass
[2] => Dirt
[3] => Rock
[4] => Rock
[5] => Grass
[6] => Rock
[7] => Lava
)
)
I'm doing it so far with a (horrible) function, shown here, but the "map" could be anything between 2 and 8 rows, and I'm struggling to see how to turn it into a neat little function that works for anything:
function makeMap($id) {
// First Row
$rowNum = 1;
$oneSeed = findSeeds($id);
$map[$rowNum][] = $oneSeed[name];
// Second Row
$rowNum = $rowNum + 1;
$twoSeed = findSeeds($oneSeed[seed1]);
$threeSeed = findSeeds($oneSeed[seed2]);
$map[$rowNum][] = $twoSeed[name];
$map[$rowNum][] = $threeSeed[name];
// Third Row
$rowNum = $rowNum + 1;
$fourSeed = findSeeds($twoSeed[seed1]);
$fiveSeed = findSeeds($twoSeed[seed2]);
$sixSeed = findSeeds($threeSeed[seed1]);
$sevenSeed = findSeeds($threeSeed[seed2]);
$map[$rowNum][] = $fourSeed[name];
$map[$rowNum][] = $fiveSeed[name];
$map[$rowNum][] = $sixSeed[name];
$map[$rowNum][] = $sevenSeed[name];
// Fourth Row
$rowNum = $rowNum + 1;
$eightSeed = findSeeds($fourSeed[seed1]);
$nineSeed = findSeeds($fourSeed[seed2]);
$tenSeed = findSeeds($fiveSeed[seed1]);
$elevenSeed = findSeeds($fiveSeed[seed2]);
$twelveSeed = findSeeds($sixSeed[seed1]);
$thirteenSeed = findSeeds($sixSeed[seed2]);
$fourteenSeed = findSeeds($sevenSeed[seed1]);
$fifteenSeed = findSeeds($sevenSeed[seed2]);
$map[$rowNum][] = $eightSeed[name];
$map[$rowNum][] = $nineSeed[name];
$map[$rowNum][] = $tenSeed[name];
$map[$rowNum][] = $elevenSeed[name];
$map[$rowNum][] = $twelveSeed[name];
$map[$rowNum][] = $thirteenSeed[name];
$map[$rowNum][] = $fourteenSeed[name];
$map[$rowNum][] = $fifteenSeed[name];
return $map;
}
It should stop when all the "row" nodes are blank, so the following only needs to return the first two "rows":
Array
(
[1] => Array
(
[0] => Wood Block
)
[2] => Array
(
[0] => Dirt
[1] => Lava
)
[3] => Array
(
[0] =>
[1] =>
[2] =>
[3] =>
)
[4] => Array
(
[0] =>
[1] =>
[2] =>
[3] =>
[4] =>
[5] =>
[6] =>
[7] =>
)
)
Any tips, hints or solutions would be GREATLY appreciated,
Thank you.
Edit: Quick note on why I'd like it in the above format - I'm then printing out the results in a table, with the first seed spanning the entire row, then breaking it down with the children underneath, like so:
$map = makeMap($_POST['theItem']);
$colspan = count(end(array_values($map)));
echo '<h3>' . $map[row1][0] . '</h3><br/>';
echo '<table>';
foreach ($map as $row) {
echo '<tr>';
foreach ( $row as $cell) {
echo '<td colspan="'. $colspan .'"><div class="seed">' . $cell . '</div></td>';
}
$colspan = $colspan / 2;
echo '</tr>';
}
echo '</table>';
<?php
$array = array('one', 'two', 'three');
for($i =1; $i<= count($array); $i++){
for($j=0; $j<$i; $j++){
$arrymulti[$i][$j]= $array[$j];
}
}
echo '<pre>';
print_r($arrymulti);
?>
Output:
Array
(
[1] => Array
(
[0] => one
)
[2] => Array
(
[0] => one
[1] => two
)
[3] => Array
(
[0] => one
[1] => two
[2] => three
)
)
DEMO
You can Use this recursive function That I Wrote It For Class
static public $map;
static function seeder($id,$Depth=0){
$Seed=findSeeds($id);
if(!$Seed){
return self::$map;
}
self::$map[$Depth][]=$Seed['name'];
self::seeder($Seed['seed1'],$Depth+1);
self::seeder($Seed['seed2'],$Depth+1);
if($Depth==0){
foreach(self::$map as $k=>$v){
$Flag=true;
foreach($v as $key=>$Value){
if($Value!="")$Flag=false;
}
if($Flag){
for($i=$k;$i<=count(self::$map);$i++){
#unset(self::$map[$i]);
}
break;
}
}
}
return self::$map;
}
Sample
print_r(seeder($ID));
The output Is similar of Your sample

Filling php array that has missing values

I've a series of arrays with values that goes from 1 to 5. Almost every array has missing values, some even dont have any values. My objective is to fill the missing values with 0. All those arrays are stored into a multidimensional array.
My array looks like:
Array
(
[1] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[2] => Array
(
[0] => 1
[1] => 5
)
[3] => Array
(
[0] => (this array has no values)
)
[4] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
etc...
)
How it should be:
Array
(
[1] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 0
[4] => 0
)
[2] => Array
(
[0] => 1
[1] => 0
[2] => 0
[3] => 0
[4] => 5
)
[3] => Array
(
[0] => 0
[1] => 0
[2] => 0
[3] => 0
[4] => 0
)
[4] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
etc...
)
Any help would be appriciated!
For each of your subarrays loop through the numbers 1 to 5, and if that value exists set its key to be one less than its value:
$newarray = array();
foreach($arr as $key => $subarr) {
for ($i = 1; $i <= 5; $i++) {
if (in_array($i, $subarr)) $newarray[$key][$i - 1] = $i;
else $newarray[$key][$i - 1] = 0;
}
}
Where $newarray is your output and $arr is your input array.
You may want to note that PHP does not truly do multidimensional arrays. It only allows you to relate 2 flat arrays together which is not true multidimensionality.
This does not work and will produce results described above.
$menu[1] = "My Training"; //not $menu[1][0]
$menu[1][1] = "To Do List";
$menu[1][2] = "Catalog";
$menu[1][3] = "Self-Report";
$menu[1][4] = "Completions";
$menu[2] = "Manager";
$menu[2][1] = "Direct Reports";
$menu[2][2] = "Incompletes";
$menu[2][3] = "Completions";
$menu[3] = "Instructor";
$menu[3][1] = "My Classes";
$menu[3][2] = "Printables";
$menu[3][3] = "Qualifications";
This does work.
$menu[1] = "My Training"; //not $menu[1][0]
$submenu[1][1] = "To Do List";
$submenu[1][2] = "Catalog";
$submenu[1][3] = "Self-Report";
$submenu[1][4] = "Completions";
$menu[2] = "Manager";
$submenu[2][1] = "Direct Reports";
$submenu[2][2] = "Incompletes";
$submenu[2][3] = "Completions";
$menu[3] = "Instructor";
$submenu[3][1] = "My Classes";
$submenu[3][2] = "Printables";
$submenu[3][3] = "Qualifications";
$submenu is only related to $menu through the first key number as there are no first dimension values to $submenu.
Something like this (array_pad() won't do the trick). $myArray is your source array. Completed array is returned in $result:
$result = array();
foreach( $myArray as $subKey=>$subArray ) {
for( $i=0; $i<5; $i++ ) {
if( isset( $subArray[$i] )) {
$result[$subKey][$i] = $subArray[$i];
} else {
$result[$subKey][$i] = 0;
}
}
}
Note, we do copy of the array. You cannot fill array in-place.
It's been many years since I wrote any PHP but something like this might do the trick I guess?
for($i = 0; $i < 5; $i++)
{
if(empty($myArray[$i])
{
$myArray[$i] = 0;
}
}

Combining two arrays PHP

I'm busy with sorting the structure of a menu in my application. Once the menu is reorderd by the user, the values (say; Menu item 1, Menu item 2, etc) are still in the same place.
Now I have two arrays, one that holds the way they are sorted (Array 1) and one that holds the values of the menu items. (Array 2)
Example of both arrays;
(Array 1, that holds the keys)
Array
(
[0] => 1
[1] => 2
[2] => 0
)
The above array's values are the keys for the new array.
(Array 2, holds the values)
Array
(
[0] => value_0
[1] => value_1
[2] => value_2
)
So I thought it would be best to create a new array which consist out of;
The values of Array 1
The values of Array 2
However, i'm running into a problem. I want the values in array 2 to stick to their keys. So lets say I change the position of value_0 to the last, the new array would look like this;
Array
(
[1] => value_1
[2] => value_2
[0] => value_0
)
Is there a way to achieve this or am I doing it completely wrong?
Edit
Ok, so multidemensional array it is. However i'm having problems creating one.
Array 1 and Array 2 both come from the database. Array 1 with the sorting order and Array 2 contains the values. Now, the values in array 2 are stored like this; value1,value2,value3. So to be able to work with them I explode on , (comma).
The results on the fetchs are both different;
For the first array it returns as many as how many values there are.
(So if there are 3 values, it will return 3 different positions.)
For the second array it will return 18 records, since this is tied to
other menu items (sub menu's etc).
So for the first array I do;
while ($row = mysql_fetch_assoc($result_query_test)) {
$positions[] = $row['position'];
}
For the second array I do;
while ($row = mysql_fetch_assoc($result_values)) {
$array_values = explode(',', $row['values']);
}
From then on i'm having problems creating the multidimensinonal array;
while ($row = mysql_fetch_assoc($result_values)) {
$array_values = explode(',', $row['values']);
foreach ($positions as $new_key) {
foreach ($array_values as $value) {
$new_array[] = array('key' => $new_key, 'value' => $value);
}
}
}
Edit two:
This is what I use now;
(Since $all_values is a multidimensional array because I have to explode on the values beforehand.)
foreach ($all_values as $values) {
foreach ($values as $key => $value) {
$new_array[] = array('key' => $positions[$key], 'value' => $value);
}
}
This is what the $new_array returns;
Array
(
[0] => Array
(
[key] => 0
[value] => value_0
)
[1] => Array
(
[key] => 2
[value] => value_2
)
[2] => Array
(
[key] => 1
[value] => value_1
)
[3] => Array
(
[key] => 0
[value] => value_0
)
[4] => Array
(
[key] => 2
[value] => value_2
)
[5] => Array
(
[key] => 1
[value] => value_1
)
Now I need to get the values and implode them with comma's. However, since not every 3 values (value_0, value_1, value_3) are together I can't do that now.
In this example there are 3 keys, (0,1,2) which should be a different array along with their values, like you did in your example:
Array (
[0] = Array (
[key] = 1,
[value] = value_1
),
[1] = Array (
[key] = 2,
[value] = value_2
),
[2] = Array (
[key] = 0,
[value] = value_0
)
)
Why not make a multidimensional array?
$arrayThree =
Array (
[0] = Array (
[key] = 1,
[value] = value_1
),
[1] = Array (
[key] = 2,
[value] = value_2
),
[2] = Array (
[key] = 0,
[value] = value_0
)
)
No matter what order they're in, the key and value are always the set.
foreach ($arrayThree as $tempArray)
{
echo $tempArray['key'];
echo $tempArray['value'];
}
Create Array
$arrayOne = array();
$arrayTwo = array();
$arrayThree = array();
$query = 'SELECT key FROM table1 ';
$result = mysql_query($query) or die(mysql_error());
while($data = mysql_fetch_assoc($result))
{
$arrayOne[] = $data['key'];
}
$query = 'SELECT value FROM table2 ';
$result = mysql_query($query) or die(mysql_error());
while($data = mysql_fetch_assoc($result))
{
$arrayTwo[] = $data['value'];
}
foreach($arrayOne as $key => $value)
{
$arrayThree[] = array('key' => $value, 'value' => $arrayTwo[$key]);
}
You can always use the mysqli or PDO versions, if you're using them.
Example Data
//THESE MIMIC YOUR SELECT RESULTS
$test_keys = array(1,2,3);
$test_values = array('value_1', 'value_2', 'value_3');
//DEFAULTS
$arrayOne = array();
$arrayTwo = array();
$arrayThree = array();
//WHILE FIRST SELECT
for($i=0;$i<count($test_keys);$i++)
{
$arrayOne[] = $test_keys[$i];
}
//WHILE SECOND SELECT
for($i=0;$i<count($test_values);$i++)
{
$arrayTwo[] = $test_values[$i];
}
//MAKE THE FINAL ARRAY
foreach($arrayOne as $key => $value)
{
$arrayThree[] = array('key' => $value, 'value' => $arrayTwo[$key]);
}
//CHECK THE OUTPUT FOR THE NEW ARRAY
echo '<pre>'.print_r($arrayThree,true).'</pre>';
Example Output
Array
(
[0] => Array
(
[key] => 1
[value] => value_1
)
[1] => Array
(
[key] => 2
[value] => value_2
)
[2] => Array
(
[key] => 3
[value] => value_3
)
)
Imploded List
$implodeValues = array_map(function($item) { return $item['value']; }, $arrayThree);
$implodeVariable = implode(',', $implodeValues);
echo $implodeVariable;
Implode Output
value_1,value_2,value_3
I think you can obtain what you want doing this:
$new = array();
for($i = 0, $len = count($array1), $i < $len, ++$i) {
$new[$array1[$i]] = $array2[$i];
}
now $new contains the values in the order you want them

Categories