Created alphabetical list in php [duplicate] - php

I have an array that already contains all it's values in alphabetical order:
Alligator
Alpha
Bear
Bees
Banana
Cat
Cougar
Now I just want to list the first letter each starts with above it like so:
A
---
Alligator
Alpha
B
---
Bear
Bees
Banana
C
---
Cat
Cougar
etc...
How can this be done?

The solution is to keep in a variable the first letter of the previously printed word, like:
$previous = null;
foreach($array as $value) {
$firstLetter = substr($value, 0, 1);
if($previous !== $firstLetter) echo "\n".$firstLetter."\n---\n\n";
$previous = $firstLetter;
echo $value."\n";
}
NB: if some entries start with a lower-case letter and others with upper-case letters, use the strcasecmp function in the test instead of !==.

here is another simple solution:-
$result = array();
foreach ($list as $item) {
$firstLetter = substr($item, 0, 1);
$result[$firstLetter][] = $item;
}
echo "<pre>"; print_r($result);
Output :-
Array (
[A] => Array
(
[0] => Alligator
[1] => Alpha
)
[B] => Array
(
[0] => Bear
[1] => Bees
[2] => Banana
)
[C] => Array
(
[0] => Cat
[1] => Cougar
)
)

Well i have three solutions.
1) Make another array containing all alphabets. Then use foreach to iterate through this array. And in nested foreach check for occurance of that letter through strpos method of php.
Here is rough code.
<?php
$alphabets = array ("A","B","C"....); //for all alphabtes
foreach($alphabets as $alphabet)
{
echo $alphabet;
foreach($myArray as $arr)
{
$pos = strpos($arr, $alphabet);
if($pos===flase)
{
//do nothing
}
else
{
echo $arr;
}
}
?>
2) second method have same logic as above. But here you dont need to make array for alphabets. You can get all alphabets this way.
<?php
foreach(range('a', 'z') as $letter) {
echo $letter;
}
?>
Php range method
3) Third solution also have same logic as above two. Here you can get alphabets by another way :)
for ($i=65; $i< =90; $i++) {
$x = chr($i);
print $x;
}

For HTML output:
<h3>A</h3>
<ol>
<li>
<em>tag count</em>
Animal
</li>
<li>
<em>tag count</em>
Aqua
</li>
<li>
<em>tag count</em>
Arthur
</li>
</ol>
<!-- if B not EXIST not show B -->
<h3>C</h3>
<ol>
<li>
<em>tag count</em>
Camel
</li>
<li>
<em>tag count</em>
Crazy
</li>
</ol>
<!-- etc -->
I change Artefact2 code and share for you
<?php $previous = null;
foreach ($dataProvider as $key => $tag) {
$firstLetter = strtoupper(substr($tag['name'], 0, 1));
if($previous !== $firstLetter) {
if($key != 0) {
echo '</ol>';
}?>
<h3 class="alpha">
<span><?php echo $firstLetter;?></span>
</h3>
<ol class="tags main">
<?php } ?>
<li class="tag">
<em><?php echo $tag['TagsCount']; ?></em>
<a href="<?php echo $tag['slug']; ?>">
<strong><?php echo ucfirst($tag['name']); ?></strong>
</a>
<span class="perc" style="width: 90px;"></span>
</li>
<?php if($key == count($dataProvider)-1) {
echo '</ol>';
}
$previous = $firstLetter;
}
?>
Best Regards www.Forum.iSYSTEMS.am

Iterate through the array and check if the current item starts with another letter than the previous one. If that's the case print your "A ---".
$currentLetter = '';
foreach ($list as $item) {
$firstLetter = substr($item, 0, 1);
if ($firstLetter !== $currentLetter) {
echo $firstLetter . "\n---\n";
$currentLetter = $firstLetter;
}
echo $item . "\n";
}

As Shivansh said above in his answer, I think that is correct way
$result = array();
foreach ($list as $item) {
$firstLetter = substr($item, 0, 1);
$result[$firstLetter][] = $item;
}
echo "<pre>"; print_r($result);
To Display the array generated by this code use
foreach ( $list as $key => $value ) {
//Do some thing with $key (A,B,C)
foreach ($value as $var){
//Do some thing with $var (Array of A, B ,C)
}
}

Related

How Split arrays into two columns With PHP

i have arrays like :
foreach($Pics AS $Allpics) {
print $Allpics;
}
Result my values:
string(40) "760_e7c5c3202c778318fdf92f406da31742.jpg"
string(40) "760_00f500b6398b4d8a0cde299730f57148.gif"
string(40) "760_54b1bb6895b636f45c56911be4f67c11.png"
string(40) "760_05986e1f46651698a8aa4f8ed17ab070.jpg"
i need Split array values into two columns !
like :
[column 1] [column 2]
760_e7c5c3202c778318fdf92f406da31742.jpg 760_54b1bb6895b636f45c56911be4f67c11.png
760_00f500b6398b4d8a0cde299730f57148.gif 760_05986e1f46651698a8aa4f8ed17ab070.jpg
Html Result like :
<div class='row'>
<div class='col-sm-6'>
760_e7c5c3202c778318fdf92f406da31742.jpg
760_54b1bb6895b636f45c56911be4f67c11.png
</div>
<div class='col-sm-6'>
760_00f500b6398b4d8a0cde299730f57148.gif
760_05986e1f46651698a8aa4f8ed17ab070.jpg
</div>
</div>
thanks for your help my friends!
You can do with array_chunk() but the problem is, if records is odd then array_chunk() create third array so, you miss last record.
It's very simple....
Use array_slice() to avoid logical error.
$Allpics = array("nature", "trees", "beauty","funny", "fun");
//counting number of records
$countRecords = count($Allpics);
//dividing array in to two array
$col1 = array_slice($Allpics, 0, $countRecords/2 + 0.5);
$col2 = array_slice($Allpics, $countRecords/2 + 0.5, $countRecords);
//making two columns
$row = array("column 1" => $col1, "column 2" => $col2);
print_r($row);
//Output
Array(
[column1] => Array(
[0] => nature
[1] => trees
[2] => beauty
) [column2] => Array(
[0] => funny
[1] => fun
)
)
This code will create two columns, records are odd so, 1st column contain 3 records and 2nd column contain 2 records. If the records are even then it will create two equal columns.
If you want same array keys from $Allpics then use true in array_slice()
Read more at http://php.net/manual/en/function.array-slice.php
use array_chunk()
array_chunk($arrays,2);
Please see the code, it may help you to achieve your goal
$arrays = array('Like' ,'Starts' , 'Moons', 'Skys');
$odd = array();
$even = array();
$i=1;
foreach($arrays as $val)
{
if($i%2==0)
$even[] = $val;
else
$odd[] = $val;
$i++;
}
print_r($odd);
print_r($even);
Use array chunks...
$arrays = ["Like" ,"Starts" , "Moons", "Skys"];
$arrays = array_chunk($arrays,2);
<div class='row'>
<div class='col-sm-6'>
<?php foreach ($arrays[0] as $key => $value) {
echo $value."<br>";
} ?>
</div>
<div class='col-sm-6'>
<?php foreach ($arrays[1] as $key1 => $value1) {
echo $value1."<br>";
} ?>
</div>
</div>
Here you can specify the column count and the algorithm will do the rest
echo "<div class='row'>";
// cant be greater than 12 because bootstrap only supp 12 columns
$columns = 2;
$arrays = array('Like' ,'Starts' , 'Moons', 'Skys');
$array_m = round(count($arrays) / $columns);
for ($i = 0; $i < $columns; $i++){
echo "<div class='col-sm-".round(12/$columns)."'>";
for ($i2= $i * $array_m; $i2 < ($i+1==$columns? count($arrays) : $array_m) ; $i2++) {
echo $arrays[$i2] . '<br>';
}
echo "</div>";
}
echo "</div>";
Please try this code
$arrays = array('Like' ,'Stars' , 'Moons', 'Skys');
$arraychunk=array_chunk($arrays,2);
?>
<div class='row'>
<?php
foreach($arraychunk as $item)
{
?><div class='col-sm-6'><?php
foreach($item as $arr)
{
echo "$arr"."<br>";
}
?></div><?php
}
?>
</div>

Looping into a multidimensional array with PHP

I've got this array:
Array
(
[0] => Array
(
[name] => System
[order] => 1
[icon] => stats.svg
[0] => Array
(
[title] => Multilingual
)
[1] => Array
(
[title] => Coloring
)
[2] => Array
(
[title] => Team work
)
[3] => Array
(
[title] => Tutorials
)
)
)
I want to loop into this to show the section name and after all the features containing in the following array.
So, this is what I made:
foreach ($features as $feature => $info) {
echo '
'.$info['name'].'
<ul class="menu-vertical bullets">
';
foreach (array_values($info) as $i => $key) {
echo '
<li>'.$key['title'].'</li>
';
}
echo '
</ul>
';
}
It works except for the first third <li> where I have the first char of name, order and icon value.
Do you know why ?
Thanks.
array_values return value of array so for info values is name, order, icon, 0, 1, ...
Your values foreach is wrong if you just want print title you can use:
foreach ($features as $feature => $info) {
echo '
'.$info['name'].'
<ul class="menu-vertical bullets">
';
//Remove some keys from info array
$removeKeys = array('name', 'order', 'icon');
$arr = $info;
foreach($removeKeys as $key) {
unset($arr[$key]);
}
foreach (array_values($arr) as $i => $key) {
echo '
<li>'.$key['title'].'</li>
';
}
echo '
</ul>
';
}
In php, array_values means all the values of the array. So array_values($info) is array($info['name'], $info['order'], $info['icon'], $info[0], $info[1], $info[2], $info[3])
in your example, you can skip the non-integer keys of the $info to get your titles:
<?php
$features = array();
$info = array();
$info['name'] = 'System';
$info['order'] = 1;
$info['icon'] = 'stats.svg';
$info[] = array('title'=>'Multilingual');
$info[] = array('title'=>'Coloring');
$features[] = $info;
foreach ($features as $feature => $info) {
echo $info['name'] . PHP_EOL;
echo '<ul class="menu-vertical bullets">' . PHP_EOL;
foreach ($info as $k => $item) {
if(!is_int($k)) continue;
echo '<li>' . $item['title'] . '</li>' . PHP_EOL;
}
echo '</ul>' . PHP_EOL;
}
BUT, your original data structure is not well designed and hard to use. For a better design, you can consider the following code, move your items to a sub array of $info:
<?php
$features = array();
$info = array();
$info['name'] = 'System';
$info['order'] = 1;
$info['icon'] = 'stats.svg';
$info['items'] = array();
$info['items'][] = array('title'=>'Multilingual');
$info['items'][] = array('title'=>'Coloring');
$features[] = $info;
foreach ($features as $feature => $info) {
echo $info['name'] . PHP_EOL;
echo '<ul class="menu-vertical bullets">' . PHP_EOL;
foreach ($info['items'] as $item) {
echo '<li>' . $item['title'] . '</li>' . PHP_EOL;
}
echo '</ul>' . PHP_EOL;
}
Sample output of the two demos:
System
<ul class="menu-vertical bullets">
<li>Multilingual</li>
<li>Coloring</li>
</ul>
It works except for the first third li where I have the first char of name, order and icon value. Do you know why ?
Why you see first chars of the values of 'name', 'order', 'icon'? Let see how PHP works.
Take the first loop as an example: foreach (array_values($info) as $i => $key)
Then $i == 0, $key == 'System'
We know that $key[0] == 'S', $key[1] == 'y', $key[2] == 's', etc.
Then you try to access $key['title'], but the string 'title' is not valid as a string offset, so it is converted to an integer by PHP: intval('title') == 0.
Then $key['title'] == $key[intval('title')] == 'S'
That's what you see.
array_value() returns the values of the array, here you will get the value of the array $info and what I understand is that is not what you need. See details for array_value().
You can check if the key for the $info is an integer. if yes, echo the title. Give this a try.
foreach ($features as $feature => $info) {
echo $info['name'].'<ul class="menu-vertical bullets">';
foreach ($info as $key => $value) {
if (is_int($key)) {
echo '<li>'.$key['title'].'</li>';
}
}
echo '</ul>';
}

Find last character in multi-dimensional associative array and delete it

I have an associative array in a foreach like this:
foreach ($mArray as $aValue) {
foreach ($aValue as $key => $value) {
echo $html->find($key,$value)
}
}
It gives me this output:
bobby
johnny
Now I would like to get the last character which is y so I did:
echo substr($TheString, -1);
But this gives me: yy because its a multi-dimensional array so it gives me the last characters in each array. What can I do to get the last character on the page y (..and delete it)?
$last_char = '';
foreach ($mArray as $aValue) {
foreach ($aValue as $key => $value) {
if(substr($html->find($key,$value), -1) == 'y'){
$last_char = $html->find($key,$value);
}
}
}
echo $last_char;
This seems to work for me
echo substr_replace($TheString,"",-3);
Try This :
echo substr($TheString, -1, 1);
OR replace a string Removing y
$s="abcdey";
$m=substr($s,0,-1);
echo substr_replace($s,$m,0)
Try This :
$array = array(
"foo" => "jonny",
"bar" => "monny",
);
$i=0;
$con=count($array);
foreach($array as $key => $value)
{
$i++;
if($i==$con)
{
$s=$value;
$m=substr($value,0,-1);
$value=substr_replace($s,$m,0);
echo "Removed Y from array of last item =".$m."</br>";
}
echo $value."</br>";
}

Converting PHP array in HTML list

I have the array below which I would like to output in a specific HTML list format.
My PHP array is as follow:
Array
(
[MAIN] => Master Product
[ID1] => Array
(
[0] => Product 1
)
[ID2] => Array
(
[0] => Product 2
[ID3] => Array
(
[0] => Product 3
)
[ID4] => Array
(
[0] => Product 4
)
)
)
The HTML list format I am looking for is as follows.
<ul id="treeview">
<li>Master Product
<ul>
<li>Product 1</li>
<li>Product 2
<ul>
<li>Product 3</li>
<li>Product 4</li>
</ul>
</li>
</ul>
</li>
</ul>
Any help would be appreciated.
Try this on for size:
function recurseTree($var){
$out = '<li>';
foreach($var as $v){
if(is_array($v)){
$out .= '<ul>'.recurseTree($v).'</ul>';
}else{
$out .= $v;
}
}
return $out.'</li>';
}
echo '<ul>'.recurseTree($yourDataArrayHere).'</ul>';
$data = array(); // your data
function toUL($data=false, $flatten=false){
$response = '<ul>';
if(false !== $data) {
foreach($data as $key=>$val) {
$response.= '<li>';
if(!is_array($val)) {
$response.= $val;
} else {
if(!$flatten){
$response.= toUL($val);
} else {
// pulls the sub array into the current list context
$response.= substr($response,0,strlen($response)-5) . toUL($val);
}
}
$response.= '</li>';
}
}
$response.= '</ul>';
return $response;
}
// Test #1 -- named values
echo toUL(array('a'=>'b','c'=>'d','e'=>array('f'=>'g')));
// Result #1
b
d
g
// Test #2 -- value lists
echo toUL(array('a','b','c',array('d','e','f')));
// Result #2
a
b
c
d
e
f
Inspired from this answer but where leaves are surounded by <li>
function recurseTree($var)
{
$out = '';
foreach ($var as $v) {
if (is_array($v)) {
$out .= '<ul>'.recurseTree($v).'</ul>';
} else {
$out .= '<li>'.$v.'</li>';
}
}
return $out;
}
And if you have associative array you can try this function:
function recurseTree($var)
{
$out = '';
foreach($var as $k => $v){
if (is_array($v)) {
$out .= '<dl>'.self::recurseTree($v).'</dl>';
} else {
$out .= '<dt>'.$k.'</dt>'.'<dd>'.$v.'</dd>';
}
}
return $out;
}

Problem with array

I am running into issues with the following code:
$ids = '"' . implode('", "', $crumbs) . '"';
$motd = array();
$dober = $db->query("SELECT id, name, msg, datetime FROM tbl_depts td INNER JOIN tbl_motd tm ON td.id = tm.deptid WHERE td.id IN (" . $ids . ")");
while ($row = $dober->fetch_array()) {
$motd[] = $row;
}
A print_r reveals this:
Array
(
[0] => Array
(
[0] => 1
[id] => 1
[1] => Management
[name] => Management
[2] => New Management Rule!
[msg] => New Management Rule!
[3] =>
[datetime] =>
)
[1] => Array
(
[0] => 2
[id] => 2
[1] => Human Resources
[name] => Human Resources
[2] => DPS
[msg] => DPS
[3] =>
[datetime] =>
)
)
As such, I cannot use this code to generate things:
foreach ($motd[] as &$value) {
if ($motd['msg'] != "") {
if ($i == 0) {
?>
<li><a href="#" title="content_<?php echo $value['id']; ?>"
class="tab active"><?php echo $value['name']; ?></a></li>
<?
} elseif ($i == $len - 1) {
?>
<li><a href="#" title="content_<?php echo $value['id']; ?>"
class="tab"><?php echo $value['name']; ?></a></li>
<?php } else { ?>
<li><a href="#" title="content_<?php echo $value['id']; ?>"
class="tab"><?php echo $value['name']; ?></a></li>
<?
}
$i++;
}
}
Any ideas on what I'm doing wrong here?
EDIT: you might find it easier to understand if you read this first: Optimize this SQL query
First - your code will not work because of this two lines:
foreach ($motd[] as &$value) {
if ($motd['msg'] != "") {
You should use $motd, not $motd[] in foreach and check $value['msg'], not $motd['msg']
Second, try to use mysql_fetch_assoc instead of mysql_fetch_array
Third - there is no initial value for $i.
1.) You might have an issue with foreach ($motd[] as &$value) {
perhaps it should be foreach ($motd as &$value) {
2.) I would rather use a for() loop instead of a foreach.
for($a=0, $cnt=count($motd)-1; $a<=$cnt; $a++ )
{
if($motd[$a]["msg"] != "" )
{
#do something here
}
}
I have rewritten your code a bit. No need to define the whole HTML several times only because there is a small change in it (I only spotted active).
$i=0;
foreach ($motd as $value) {
if ($value['msg'] != "") {
$active = $i == 0 ? ' active' : ''; //based on the value of `$i`
?>
<li>
<a href="#"
title="content_<?php echo $value['id']; ?>"
class="tab<?php echo $active?>"><?php echo $value['name']; ?></a></li>
<?php
$i++;
}
}
As I noted in the comments earlier:
In foreach you have to specify the array itself, you do not need [].
Always initialize your $i.
You do not need &$value, you only need that reference if you want to modify your array in the foreach.

Categories