Group PHP arrays by key value - php

Basically I'm trying to group my arrays like this:
Shopping
Amazon
Social
Amoeblo
American express
By using below PHP code:
<?php
echo '<ul id="list"><h2 class="searchresults"></h2>';
foreach($records as $catval) {
$sitechar = $catval->site_category;
echo '<h3 id="disappear">'. strtoupper($sitechar) .'</h3>';
echo '<li class="siteli"><a href="#" class="add">';
echo '<p id="text-site">'.$catval->site_name. '</p></a>';
echo '</li>';
}
echo '</ul>';
?>
But I'm getting values only like below.
Shopping
Amazon
Social
Amoeblo
Social
American express
I'm not getting the exact PHP sorting to use for this.

I would create a new array with categories as keys for arrays with the sites.
<?php
$arr = array();
// First create multidimensional array with categories as keys for site arrays
foreach($records as $catval) {
$sitechar = $catval->site_category;
if (!array_key_exists($sitechar, $arr)) {
// Set new array for a category if it does not exist
$arr[$sitechar] = array();
}
// Add site to category
$arr[$sitechar][] = array(
"name"=>$catval->site_name,
"image"=>$catval->site_img
);
}
// Then iterate the new array of categories
echo ("<ul>");
foreach($arr as $category => $sites) {
echo("<h3>" . $site_category "</h3>");
// Iterate array of sites
foreach($sites as $site) {
echo("<li>" . $site["name"] . "-" , $site["image"] . "</li>");
}
}
echo("</ul>");
?>

You can do it using a foreach and ksort
Let $your_array be the array you mentioned above
$res_array = array();
foreach($your_array as $val){
$res_array[$val->site_category][] = $val->site_name;
}
ksort($res_array);
print_r($res_array);
OR search for multisort in php which will solve your problem :)

$tmp = null;
echo '<ul id="list"><h2 class="searchresults"></h2>';
foreach($records as $catval) {
$myHtml = makeHtml($catval,$tmp);
echo $myHtml;
$tmp = $catval->site_category;
}
echo '</ul>';
function makeHtml($catval,$tmp){
if($tmp != $catval->site_category){ $html .= '<h3 id="disappear">'. strtoupper($catval->site_category) .'</h3>';}
$html .='<li class="siteli"><p id="text-site">'.$catval->site_name. '</p></li>';
return $html;
}

Related

Traverse an array or cross an array

I am fairly new to php and trying to get echo "<p>" .get_the_tags($author_post). "</p>"; to echo out the tags associated with the post its listing in the loop.
I was told to "you need to traverse the array" and "This returns an array of tags. Then you have to cross the array if you want to echo it out."
but was not told how to accomplish this. I am unsure how to proceed.
Here is the full code.
if ($author_posts) {
echo '<ul>';
$i = 0;
foreach ($author_posts as $author_post) {
/* excluded categories */
if (has_category(explode(',', $atts['exclude']), $author_post->ID)) :
continue;
endif;
$postdate = date_i18n( get_option( 'date_format' ), strtotime($author_post->post_date)).' - ';
echo '<li>';
echo ($atts['postdate'] ? $postdate : ''). ''.$author_post->post_title.'';
$categories = get_the_category( $author_post->ID );
$list_cats =null;
foreach ($categories as $cat) :
$list_cats .= $cat->name.", ";
endforeach;
$list_cats = substr($list_cats, 0, -2);
echo "<p>" .get_the_tags($author_post). "</p>";
echo '</li>';
$i++;
if ($atts['postsperauthor'] > -1) :
if ($i >= $atts['postsperauthor']) :
break;
endif;
endif;
}
}
Thanks for any help you can provide
I guess your get_the_tags() return an array
try this:
$tags = get_the_tags($author_post);
$tagNames = [];
foreach ( $tags as $tag ) {
$tagNames[] = $tag->name
}
echo implode(',',$tagNames)
echo '</div>';
echo '</li>';
BTW , this syntax is a bit old...

How do i display list items from php array

Ive been trying make this display as html list items it just a string that i explode then loop over each item i cant get it to out put correctly. Could some one please show me where im going wrong or suggest an new approch.
this is what ive tried
$path = "1/2/3/4";
$expath = explode("/",$path);
$ret = '';
echo '<ul>';
foreach ($expath as $pitem) {
echo '<li><a href='.$ret .= $pitem. "/".'>'.$pitem.'</a></li>';
}
echo '</ul>';
.
Desired out put on hrefs
1
1/2
1/2/3
1/2/3/4
Desired visual out LIs
1
2
3
4
Output i get be warned
1
12/>212/>23/>312/>23/>34/>4
$path = "1/2/3/4";
$expath = explode("/", $path);
echo '<ul>';
foreach ($expath as $i => $pitem) {
$slice = array_slice($expath, 0, $i + 1);
$path = implode('/', $slice);
echo '<li>' . $pitem . '</li>';
}
echo '</ul>';
$list = explode("/", "1/2/3/4");
This will create an array $list as:
echo $list[0]; // 1
echo $list[1]; // 2
echo $list[2]; // 3
echo $list[3]; // 4
This line is the problem: echo '<li><a href='.$ret .= $pitem. "/".'>'.$pitem.'</a></li>';
Should be formatted like:
echo "<li><a href='{$ret}={$pitem}/'>{$pitem}</a></li>";
or echo '<li>'.$pitem.'</li>';
Its because your $ret. Place that inside the loop. In your code you concatenate $pitem with $ret all older $ret values also get concat.
Try
<?php
$path = "1/2/3/4";
$expath = explode("/",$path);
echo '<ul>';
foreach ($expath as $pitem) {
$ret = '';
echo '<li><a href='.$ret .= $pitem. "/".'>'.$pitem.'</a></li>';
}
echo '</ul>';
If you want = sign tobe there in the url then just change echo by following
echo "<li><a href='$ret=$pitem/'>$pitem</a></li>";
PHP echo with double quotes will print variable value.

How to perform arrays of arrays using list method of php?

Code is as follows:-
$student=array(
"HINDI"=>array("marks"=>"96","grade"=>"1st"),
"ENGLISH"=>array("marks"=>"92","grade"=>"1st")
);
In above code I want to get the output like using php list() method
subject =hindi marks=96 grade=1st
subject =english marks=94 grade=1st
Thank you :)
You can do it without a list just by using foreach like
$student=array(
"HINDI"=>array("marks"=>"96","grade"=>"1st"),
"ENGLISH"=>array("marks"=>"92","grade"=>"1st")
);
foreach ($student as $subject => $student)
{
echo "subject=".$subject." marks=".$student['marks']." grade=".$student['grade']." "; // add strtolower to get lower char
}
You can't retrieve keys using list, but you can get sub arrays like this:
<?php
list($a, list($aa, $ab, $ac)) = array(0, array(1, 2, 3));
echo $a;
echo '<br>';
echo $aa;
echo '<br>';
echo $ab;
echo '<br>';
echo $ac;
echo '<br>';
?>
But if you forget about list(), you can do this and get the output you asked for:
<?php
$students=array(
"HINDI"=>array("marks"=>"96","grade"=>"1st"),
"ENGLISH"=>array("marks"=>"92","grade"=>"1st")
);
$output = '';
foreach($students as $name => $student)
{
$output .= ' subject='.$name;
foreach($student as $key => $value)
$output .= ' '.$key.'='.$value;
}
echo $output;
?>

What is the quickest way to randomize a data set?

For a multiple choice quiz application i would like to show the dummy answers with the correct answer. But with the correct answer being in a different position at each different question.
This is what i've tried but it doesn't seem to be working:
if ($question->type == 1)
{
echo "<div id='dummy_answers'>";
//Show Dummy
echo '<h3>Dummy Answers</h3>';
//Get Dummy Answers
$query = $this->test_model->getDummyAnswers($question->id);
$dummy_num = 1;
foreach ($query->result() as $row)
{
$rand_number = rand(1, 3);
if ($dummy_num == $rand_number)
{
$dummy_num = $rand_number + 2;
echo '<h4>Answer '.$dummy_num.'</h4>';
echo '<p>';
echo $row->option;
echo '</p>';
//Now echo the real answer
echo '<h4>Answer '.$rand_number.'</h4>';
echo '<p>';
echo $row->option;
echo '</p>'; //Get id's for each.echo $row->id;
}
else
{
echo '<h4>Answer '.$dummy_num.'</h4>';
echo '<p>';
echo $row->option;
echo '</p>';
$dummy_num++;
}
}
echo '</div>';
echo ' <hr/>';
}
?>
You should use shuffle function.
In your case it will be:
if ($question->type == 1)
{
echo "<div id='dummy_answers'>";
//Show Dummy
echo '<h3>Dummy Answers</h3>';
//Get Dummy Answers
$query = $this->test_model->getDummyAnswers($question->id);
$answers=$query->result();
shuffle($answers);
foreach ($answers as $nr=>$row)
{
echo '<h4>Answer '.($nr+1).'</h4>';
echo '<p>';
echo $row->option;
echo '</p>';
}
echo '</div>';
echo ' <hr/>';
}
?>
Put the answers in an array the use shuffle
$random_array = shuffle($answers);
All you need to do is put the keys for your answers in an array and call shuffle(). Something like this:
$keys = array_keys($answers);
shuffle($keys);
for ($key in $keys) {
echo $answers[$key];
}
I would suggest putting all the answers into an array and using the shuffle() function to randomize them. Once they're shuffled, just iterate the array with a loop and build the markup.
You could put the results into an array (1 correct and 3 incorrect), then shuffle, then output them?
$answers = array();
array_push($answers, "answer1");
array_push($answers, "answer2");
array_push($answers, "answer3");
array_push($answers, "answer4");
shuffle($answers);
foreach ($answers as $answer) {
echo $answer;
}

XML Data into PHP Array

I am getting data from XML files that I need to make into an array in PHP. Can any one tell me how to fill PHP array when count is unknown?
function getFeed($feed_url)
{
$content = file_get_contents($feed_url);
$x = new SimpleXmlElement($content);
echo "<ul>";
foreach($x->channel->item as $entry)
{
echo "
<li>
<a href='$entry->link' title='$entry->title' target='_new'> " . $entry->title . "</a>
</li>";
}
echo "</ul>";
}
Question: can any one tell me how to fill php array when count is unknown
Declare the array and add items to it like so or use array_push
$something = array();
$something[] = 'first item';
$something[] = 'second item';
Hope this works for you:
$c = 0;
$entries = Array();
foreach($x->channel->item as $entry) {
echo "
<li>
<a href='$entry->link' title='$entry->title' target='_new'> " . $entry->title . " </a>
</li>";
$entries[$c] = $entry->title;
$c++;
}
function getFeed($feed_url) {
$content = file_get_contents($feed_url);
$x = new SimpleXmlElement($content);
$count = 0;
$data = array();
foreach($x->channel->item as $entry) {
$data[$count]['link'] = $entry->link;
$data[$count]['title'] = $entry->title;
$count++;
}
return $data;
}
might be a better solution. You can then manipulate the data in a more flexible way; keeping the data from presentation separate. Simply loop through $data and output it as you require.
You can always use array_push() or basic array method.
http://php.net/manual/en/function.array-push.php
Array Push
$list = array();
array_push($list,$element);
or
$list[] = $element;
Full Code
<?php
function getFeed($feed_url) {
$content = file_get_contents($feed_url);
$x = new SimpleXmlElement($content);
$list = array();
foreach($x->channel->item as $entry) {
array_push($list,$entry);
}
return $list;
}
$list = getFeed("url");
echo "<ul>";
foreach($list as $entry) {
echo "
<li>
<a href='$entry->link' title='$entry->title' target='_new'> " . $entry->title . "</a>
</li>";
}
echo "</ul>";
?>
I can see you print an HTML list while navigating through XML nodes. So if I got your question, you also need to fill an array (in the meanwhile) with the data taken from the XML, actually converting your XML into an array... is that what you want?
Then, you just need to declare an empty array before the foreach statement:
$arr = array();
and then, inside your foreach, add new fields to the array this way:
$arr[] = $entry;
If you need to specify more fields, you can do something like that:
$arr[] = array(
'field' => $entry->fieldvalue
);`
Hope this helps!

Categories