I'm using ThumbsUp V2 Voting Script and i'm trying to display the posts based on the number of votes:
<?php $items = ThumbsUp::items()->orderby('votes_total')->get() ?>
The values are stored in mysql so i thought of:
$display = mysql_query("SELECT * FROM banat");
$items = ThumbsUp::items($display)->orderby('votes_total')->get() ;
But i thik i've definitely done this wrong since it's just displaying an output:
Array
If you get an array, you must loop on it to show the data. You cannot just do an echo on a var that is an array. You should have something like this:
foreach($items as $item)
{
echo $item;
}
Your $items is an array, and I assumed you attempted to
echo $items;
Instead you will need to loop over it:
foreach ($items as $item) {
// View the structure of `$item`
print_r($item);
}
If you only expect $items to hold one thing, then just do:
print_r($items[0]);
Related
In PHP I am getting an array from foreach. I am JSON encoding and showing all the results at once. This works fine. But what if I need to display array items one by one as foreach still continues?
<?php
$array = //somearray;
$data_arr = array();
foreach($array as $arr){
//do something
$data_arr[] = $arr;
}
echo json_encode(array('success'=>true,'data'=>$data_arr));
//here i can display the data in my jquery using each function
//i can display the whole data at once after the foreach is completed
//what i need is i want to display first element of data_arr after its loop is completed and then the second element and so on
?>
Did you try http://www.php.net/array_shift ? its php function you need to call this function after foreach
<?php
foreach($array as $arr){
//do something
$data_arr[] = $arr;
}
print_r array_shift($data_arr);
//Print First array value from this $data_arr list.
?>
Thanks.
What you looking for is Streaming Response.
Checkout following link to learn how to do that.
https://www.sitepoint.com/php-streaming-output-buffering-explained/
I have an array that looks like this:
Id = "ADA001"
Stock: 15
The array has about 1700 records that looks the same, how would I search the array for the ID 1 and return the stock?
Edit: I will need to access the stock of each one of these 17000 records
Edit: I have been getting some help from Daniel Centore, he told me to set an arrays primary key to the id of the item and that it is equal to the stock, but I can't get it to work.
I am currently getting the data from an MySQL database and I store it in an array, like so:
$data[] = array();
$getdisposabletest = mysqli_query($connect, "Select id, disposable FROM products");
while ($z = mysqli_fetch_array($getdisposabletest)) {
$data = $z;
}
Now when I use Daniels code that looks like this:
$myMap = [];
foreach($data as $item) {
$myMap[$item['id']] = $item['disposable'];
}
It doesn't return anything when I try to echo my product with the ID "ADA001"
echo $myMap["ADA001"];
Also when I do "count($mymap)" it says its 2 records big, when it should be muuuch larger than that?
Thanks for help
I would use array_filter. Return the result of a comparitor.
$results = array_filter($targetArray, function($el) {
return $el === 1;
});
Edit: Now that it has been made clear that the OP wants to query from thousands of items, the correct way to do this is to make the Id the key to a map in PHP, like this:
$myMap = [];
foreach($array as $item) {
$myMap[$item['Id']] = $item['Stock'];
}
Now, whenever you want to access item '12', simply use $myMap['12'].
The reason this is faster is because of something called algorithmic complexity. You should read about Big-O notation for more info. Essentially, the first operation here is on the order of n and then looping through each of the items that comes out is on the order of n*log(n), so the final result is on the order of n*log(n) which is the best you'll be able to do without more information. However, if you were only accessing one element, just accessing that one element via MySQL would be better because it would be on the order of log(n), which is faster.
Edit 2: Also notice that if you were to access mutliple fields (ie not just the stock) you could do the following:
$myMap = [];
foreach($array as $item) {
$myMap[$item['Id']] = $item;
}
And simply access item 12's stock like this: $myMap['12']['stock'] or its name like this: $myMap['12']['name'].
You would do something like this.
$newArray=[];
foreach($array as $item){
if($item['Id'] === 1){
$newArray[] = $item;
}
}
$stockArray = array_column($newArray,'Stock');
Given an empty array $items = array();
Why should I use the following code (which I've seen used before):
if (count($items) > 0) {
foreach ($items as $item) // do stuff here
}
instead of just
foreach ($items as $item) // do stuff here
If count($items) === 0 the loop won't execute anyway??
You don't generally need to do the check. I see lots of code with that check, but it's often unnecessary, and I think it's usually due to ignorance on the part of the programmer. A similar pattern that I frequently see is after database queries:
if (mysqli_num_rows($stmt) > 0) {
while ($row = mysqli_fetch_assoc($stmt)) {
...
}
}
This test is also unnecessary; if no rows were found, the first fetch will return false, and the loop will stop.
The only case where it's useful is if you want to tell the user that there were no results, instead of just displaying an empty table. So you might do:
if (count($items) > 0) {
echo "<table>";
foreach ($items as $item) {
// display table row
}
echo "</table>";
} else {
echo "<b>No data found!</b>";
}
It actually depends on what you want to do. As the comments have pointed out, you may want an empty array to be a special case, so you'd like to handle that case differently. Otherwise, no warning will be thrown if you execute foreach on an empty array, you just won't get any results. A typical check you should execute is if $items is an array at all, or cast $items into an array anyway to avoid getting that warning. If you did that and $items would be generally be converted into an array of one value, i.e. the value $items had at that point.
e.g.
$items = 2;
foreach((array)$items as $item) {
print $item; //will print 2 alright
}
or
if(is_array($items)) {
foreach($items as $item) {
print $item;
}
}
else {
// do something here
}
I'm trying to get the result of my foreach loop into an url to do a simplexml_load_file with.
So it goes like this:
(...) //SimpleXML_load_file to get $feed1
$x=1;
$count=$feed1->Count; //get a count for total number of loop from XML
foreach ($feed1->IdList->Id as $item1){
echo $item1;
if($count > $x) {
echo ',';} //Because I need coma after every Id, except the last one.
$x++;
}
The two echo are just to see the result. It gives me something like:
22927669,22039496,21326191,18396266,18295747,17360921,15705350,15681025,15254092,12939407,11943825,11495650,10964843
I would like to put that in a url to make a simplexml_load_file just like that
$feed_url = 'http://www.whatevergoeshere'. $RESULT_OF_FOREACH . 'someothertext';
So it would look like:
$feed_url = 'http://www.whatevergoeshere22927669,22039496,21326191,18396266,18295747,17360921,15705350,15681025,15254092,12939407,11943825,11495650,10964843someothertext';
I've try to store it into an array or a function and then call it into the feed_url but it did not work the way I tried it.
I hope it's clear, I'll answer fast to questions if not.
Thanks.
It's really difficult to make out what you want, so I'm going to guess you want to store the list as a comma delimited string in a variable. the easiest way is to implode the array of ids
$ids = array();
foreach ($feed1->IdList->Id as $item1){
$ids[] = (string) $item1;
}
$RESULT_OF_FOREACH = implode(',', $ids);
$feed_url = 'http://www.whatevergoeshere'. $RESULT_OF_FOREACH . 'someothertext';
How do you count the results inside a foreach then store that value in a variable to be used on another foreach.
Example. This foreach returns 5 items
foreach ($xml->items as $item) {
echo "$item->name";
echo "$item->address";
}
Now I want that the foreach above be counted and stored in say $totalitems and be used on another foreach. This second foreach also counts its results and store in $totalitems2. Something like this:
foreach ($xml->items as $item) { //Same source but they will be displayed separately based on a condition.
echo "$item->name";
echo "$item->address";
if_blah_blah_meet_condition_then_break;
}
So basically what I want here is to restrict the total number of items being displayed on both foreach combined. $totalitems and $totalitems2 should have the sum of 8. 8 is the number I want limit the items returned. Doesn't matter if the other foreach has more items than the other. 3 and 5. 4 and 4. 6 and 2. Etc.
How can I achieve this? Please advice.
Just use the simple iterator ++ methods. When you are on the second foreach, watch for when $i passes the number that you want to stop it.
Code:
$i = 0;
foreach ($xml->items as $item) {
echo "$item->name";
echo "$item->address";
$i++;
}
foreach ($xml->items as $item) {
echo "$item->name";
echo "$item->address";
$i++;
if ($i > 5) { // or whatever the number is
break;
}
}
$totalItems = count($xml->items);
foreach ($xml->items as $item) {
echo "$item->name";
echo "$item->address";
}
Just use count($xml->items) and that value in the condition, inside the loop.
It seems your array is stored in xml->items therefor, you only would have to save it in another variable if you want to store it.
foreach ($xml->items as $cont=>$item) {
echo "$item->name";
echo "$item->address";
if($cont<8){
$totalItems_one[] = $item;
}
}
//whatever changes you do to $xml->items
foreach ($xml->items as $cont=>$item) {
echo "$item->name";
echo "$item->address";
if($cont<8){
$totalItems_two[] = $item;
}
}
Like this you have the two new arrays totalItems_one and totalItems_two and you can get the number of items just doing count($totalItems_one) or count($totalItems_two) whenever you want.