output specific array key for each result - php

i have a search engine for my page. as a result i would like to ouput the array key for each result.
so i have this code:
$results = search($keywords);
$results_num = count($results); //what shows the message how many items were found
if (!empty($errors){
foreach ($results as $result){
echo "this is result: "
.$result['key']; //thought would be the solution, its not.
}
} else {
foreach ($errors as $error){
$error;
}
}
i also tried using a counter like:
$results = search($keywords);
$results_num = count($results); //what shows the message how many items were found
$counter = 0;
if (!empty($errors){
foreach ($results as $result){
$counter++;
echo "this is result: "
.$counter;
}
} else {
foreach ($errors as $error){
$error;
}
}
what doesnt work as i thought and is still not that professional.
so if there is someone who could tell me how to solve this i really would appreciate. thanks a lot.

foreach ($results as $key => $result) {
echo 'this is result: ' . $key;
}
The current key will be assigned to $key and the value for that property will be assigned to $result
http://php.net/manual/en/control-structures.foreach.php
edit
In response to your comments, I think this is what you're trying to achieve:-
$i=0;
foreach($results as $result) {
echo 'this is result: ' . ++$i;
}

foreach($arr as $key=>$val){
//do something with key and value
}

Here in code you can check first if $results array is not empty because sometime due to empty $results array foreach generates error
/*Check if $results array is empty or not*/
if(!empty($results)){
foreach ($results as $key=>$result){
/*result you want to show here according conditions*/
}
}

Related

Filtering an array with foreach and for loop

I'm pulling data from mssql database into an array called
$results2
I need to echo out each 'Item' only one time, so this example should only echo out:
"52PTC84C25" and "0118SGUANN-R"
I can do this easily with:
$uniqueItems = array_unique(array_map(function ($i) { return $i['ITEM']; }, $results2));
The issue is when i try to echo out the other items associated with those values. I'm not sure how to even begin on echoing this data. I've tried:
foreach($uniquePids as $items)
{
echo $items."<br />";
foreach($results2 as $row)
{
echo $row['STK_ROOM']."-".$row['BIN']."<br />";
}
}
This returns close to what I need, but not exactly:
This is what I need:
Assuming your resultset is ordered by ITEM...
$item = null; // set non-matching default value
foreach ($results2 as $row) {
if($row['ITEM'] != $item) {
echo "{$row['ITEM']}<br>"; // only echo first occurrence
}
echo "{$row['STK_ROOM']}-{$row['BIN']}<br>";
$item = $row['ITEM']; // update temp variable
}
The if condition in the code will check if the ITEM has already been printed or not.
$ary = array();
foreach($results2 as $row)
{
if(!in_array($row['ITEM'], $ary))
{
echo $row['STK_ROOM']."-".$row['BIN']."<br />";
$ary[] = $row['ITEM'];
}
}

modify key in a foreach loop php

I want to change the value of the $key because I have array_splice inside the loop which change the position of my values so - it mess up the value I need in a specific place.
I tried $key-- but it doesn't work.
for example when I print the $key after I do echo $key it's fine but when I echo $key just after the foreach loop I get the worng value.
Any ideas?
foreach ($cut as $key => $value) {
echo "foreach key:".$key."<br>";
if(in_array($value,$operators))
{
if($value == '||')
{
echo "found || in position:".$key."<br>";
if(($key+1<sizeof($cut)))
{
$multi = new multi;
echo "<br>"."key-1: ";
print_r($cut[$key-1]);
echo"<br>";
echo "<br>"."key+1: ";
print_r($cut[$key+1]);
echo"<br>";
$res = $multi->orex($cut[$key-1],$cut[$key+1],$numString);
$cut[$key-1]= $res;
array_splice($cut,$key,1);
array_splice($cut,$key,1);
$key--; //here trying to change the key
echo "new string:";
print_r($cut);
echo "<br>";
echo "key:".$key."<br>";
}
}
}
}
Updated
I don't think it is a good idea to change the array itself inside the foreach loop. So please crete another array and fill data into it, which will be your result array. This method works well when your array data is not big, in other words, most situations.
Origin
I don't know what do you mean. Let me give it a guess...
You want:
foreach($arr as $key=>$val){
$newkey = /* what new key do you want? */
$arr[$newkey] = $arr[$key];
unset($arr[$key]);
}

php foreach loop with continue if value has already been echoed

I have a foreach loop and I need to add a continue if the value has already been echoed. I can't find the right syntax. The loop:
foreach ($results as $result) {
echo $result->date . "<br />";
}
But I need to add in a continue so that if the value has already been echoed, and it comes up again in the loop it gets skipped. I can't quite get the if/continue statement quite right.
Thoughts, suggestions, ideas?
As mentioned by #JonathanKuhn in the comments - here is how you would run that loop:
$already_echoed = array();
foreach ($results as $result) {
if (!in_array($result->date, $already_echoed)) { //check if current date is in the already_echoed array
echo $result->date . "<br />";
}
$already_echoed[] = $result->date; //store all dates in an array to check against.
}
$echoedArray = array();
foreach ($results as $result) {
if (isset($echoedArray[$result->date])) {
continue;
}
echo $result->date . "<br />";
$echoedArray[$result->date] = true;
}
$alreadyOutput = array();
foreach ($results as $result) {
if(in_array($result->date, $alreadyOutput)){
continue;
}
$alreadyOutput[] = $result->date;
echo $result->date . "<br />";
}

Outputing 2 object arrays in foreach cycle

below is example how mine arrays do look, i want them combine so i can output both title, votes and ratings in one line.
foreach ($items->items as $item) {
echo $item->title;
foreach ($results->resx as $res) {
echo $res->votes;
echo $res->ratings;
}
I'd like to have this, but i know this isn't right.
foreach ($items as $item) ($results as $res) {
echo $res->votes;
echo $res->ratings;
echo $item->title;
}
You can use array_merge() for that, like so:
foreach (array_merge($results, $items) as $item) {
echo isset($item->title) ? $item->title : $item->votes .'<br>'. $item->ratings;
}
UPDATE:
Changed how to print values as the objects from merged array can only have one of the two groups of properties.
UPDATE 2:
After some OP's notes that made more clear what his scenario is, and now given the assumption that both $results and $items arrays have the same number of elements, an update solution is as follows:
while ((list(, $it) = each($items)) && (list(, $rs) = each($results))) {
echo $it->title;
echo $rs->votes;
echo $rs->ratings . '<br>';
}

Printing an array in php

Now I understand that you cant just use echo to print the contents of an array and you have to use foreach but for some reason this is not working. Any ideas?
$rows = $stmt->fetchAll();
foreach ($rows as $key=>$row)
{
echo "My value at $key is $row";
}
}
Output:
My value at 0 is ArrayMy value at 1 is ArrayMy value at 2 is Array
It appears you've fetched something from PDO using fetchAll.
This method returns an array of arrays (rows). The inner arrays have column_name => value elements. So for example if you retrieved the column 'firstName' and 'lastName', these values for the first record will be $rows[0]['firstName'] and $rows[0]['lastName'] respectivelly.
The proper way to do this would be:
$rows = $stmt->fetchAll();
foreach ($rows as $key => $row) {
foreach ($row as $column => $value) {
echo "My $column value for row $key is $value\n";
}
}
Protip: Watch the parentheses alignment, this doesn't matter for correctness but makes the code more readable :)
Looks like a multi-dimensional array to me. Try var_dump or print_r
var_dump($rows);
print_r($rows);
$row is another array which can not be converted directly to string. You can use this function to check array content.
function d($data)
{
echo '<pre>';
print_r($data);
echo '</pre>';
}
d($stmt->fetchAll());
and better you do this (if you forgot to remove its calling doesn't harm your site)
define('ENVIRONMENT', 'development');
function d($data)
{
if(ENVIRONMENT == 'development')
{
echo '<pre>';
print_r($data);
echo '</pre>';
}
}
d($stmt->fetchAll());
Try this to debug the content of $row:
$rows = $stmt->fetchAll();
foreach ($rows as $key=>$row)
{
echo "First key: $key | ";
foreach($row as $subkey => $subrow)
{
echo "Subkey: $subkey | Value: $subrow <br />";
}
}
Addiotinally, it's important to use functions like var_dump(), print_r() and var_export(), they will prevent a lot of problems for you.
//<pre> tag will give you a well formatted version of var_dump
echo "<pre>";
var_dump($rows);
echo "</pre>";
//#parram $data-array,$d-if true then die by default it is false
//#author Your name
function p($data,$d = false){
echo "<pre>";
print_r($data);
echo "</pre>";
if($d == TRUE){
die();
}
} // END OF FUNCTION
Use this function every time whenver you need to string or array it will wroks just GREAT.
There are 2 Patameters
1.$data - It can be Array or String
2.$d - By Default it is FALSE but if you set to true then it will execute die() function
In your case you can write like this..
$rows = $stmt->fetchAll();
foreach ($rows as $key=>$row) {
p($rows); // to use p function use above code for p() in your code
}

Categories