Im getting the array from a function then using it on a foreach, it prints all rows, how can i print specific row when im using [0] after array it displays only first letters of both rows.
PHP FUNCTION:
public function selectedOffer($model_id){
$qq = mysqli_query($this->connection,"SELECT offerId FROM offers WHERE model_id='$model_id' ORDER BY id ASC");
$results = array();
while ($result = mysqli_fetch_array($qq)) {
$results[] = $result;
}
return $results;
}
FOREACH PHP
foreach ($mUser->selectedOffer($modelid) as $key) {
echo $key['offerId'][0];
}
also when i remove the [0] it prints both rows.
My question is how to print the first or second or which row i want?
To get specific/ first row,s column
$data = $mUser->selectedOffer($modelid);
echo $data[0]["offerId"];
And all rows column
foreach ($data as $key) {
echo $key['offerId'];
}
Use implode and array_column to echo a complete array column in one line of code:
echo implode("", array_column($yourarray, "offerId"));
The first argument of the implode is what should join the items in the array.
Your and the accepted answer has nothing that is why it's "", but it can be replaced with say: "<br>\n" if you want new line between each item of the array.
Related
I have 2 foreach loop's where i get new results from my first db and i have second foreach where i get data from second db
My first foreach code is:
foreach($_existing_data_result as $result) {
echo $result->name.'<br>';
}
second foreach:
foreach($_new_data_result as $resultNew) {
echo $resultNew->name.'<br>';
}
I need to check on second foreach if result exist in first then ignore this result, i tried it with in_array()but i always see double names...
Second foreach, change it to this:
foreach($_new_data_result as $resultNew) {
if (!in_array($resultNew,$_existing_data_result))
echo $resultNew->name.'<br>';
}
This will work assuming that entire $resultNew object exist in $_existing_data_result and is identical.
//Use array_diff instead. Like
$new_array = array_diff($_existing_data_result, $_new_data_result);
First get all names from the first array:
$names = array_map(
create_function('$object', 'return $object->name;'),
$app_items);
Then in second foreach check if the name exists in names array:
foreach($_new_data_result as $resultNew) {
if(!in_array($resultNew->name, $names) {
echo $resultNew->name.'<br>';
}
}
$names = array();
foreach($_existing_data_result as $result) {
echo $result->name.'<br>';
$names[$result->name] = 1;
}
foreach($_new_data_result as $resultNew) {
if (!isset($names[$resultNew->name])) {
echo $resultNew->name.'<br>';
}
}
I queried a table into an array but I would like to exclude certain values from one of the columns as to spits out each row. For example.
foreach($results as $row)
{
if($row['sku'] != "sku-1"){
echo $row['sku']." ";
}
}
So lets say the table has 4 rows with a value of sku-1, sku-2, sku-3 and sku-4. The above Foreach code would echo out "sku-2 sku-3 sku-4". Is there a way I can make an array of what values I would want to exclude? Like I'd have an array called $skuarray = "sku-2, sku-4" and instead of
if($row['sku'] != "sku-2" || $row['sku'] != "sku-4"){
have that $skuarray in there where it'll echo "sku-1, sku-3"? Thanks!
EDIT
I could somehow exclude it when I query it. I'm querying it from table SKUTABLE and the column is SKU. The problem is I need to exclude unique values from column SKU so I thought if there was an easy way to just throw in all the ones I want to exclude into an array that'd be great.
You could use the array_diff(array1, array2, [...arrayN]) function, which takes at least two arrays, and returns an array of only those values of array1 which are not in any of the subsequent arrays. Example:
$input = array(0=>'sku-1',1=>'sku-2',2=>'sku-3',3=>'sku-4');
$exclude = array('sku-1','sku-3','sku-4');
$result = array_diff($input, $exclude);
print_r($result);
Will print
array(1=>'sku-2');
Use in_array:
$skuarray = array("sku-2", "sku-4");
foreach($results as $row)
{
if(!in_array($row['sku'], $skuarray)){
echo $row['sku']." ";
}
}
You can use array_filter in combination with in_array.
$filtered_results = array_filter($results, function ($row) {
return in_array($row["sku"], $skuarray) === false;
});
When looping through array using the 'while' I get good results, but when I do the same with foreach I don't get the same. The SELECT statement returns two rows:
731
732
$data = $mysqli->query("SELECT ...");
while($item = $data->fetch_array())
{
echo $item[0]."<br />";
}
This returns:
731
732
foreach ($data->fetch_array() as $item)
{
echo $item."<br />";
}
This returns:
731
731
What am I doing wrong in second aproach with 'foreach'?
Thank you very much!
That's because the array represents a single row in the returned result set. In your foreach loop, $data->fetch_array() will only ever be executed once and that will hold only a single row (which is 731). You'll have to cal fetch_array() again to get the next record. You'll have to use a while loop to get the records and push them into an array first, and then use foreach:
$resultset = array();
while($item = $data->fetch_array()) {
$resultset[] = $item;
}
foreach ($resultset as $row) {
echo $row;
}
Every time whe you call the fetch_array method, it returns one row from the DB as an array with the values of the fields.
So it does NOT return all the rows, but all the fields in one row.
And when you call it again, it will return array with the fields in the second row.
When all the rows in the query are returned, fetch_array() returns FALSE. In the while loop the $row variable becomes false and the lopp stops.
I currently have an array in php that stores product names, normally 5 - 10. I would like to create something where the results of a SQL query is matched against the array to make sure they are all correct, and if not to show an error.
So far I have put the results into an array, then ran the query to get the results. I believe I need to put some sort of while loop with the results of the query and check the array in that while loop?
You have the array with the product name($products) and the results of the query($row).
While you loop trough the results you can check if the element is present,otherwise echo error and break the loop:
While(...) {
if(!in_array($row['retrivedprod'],$products)) {
echo 'error';
break;
}
}
You can cycle while receiving results from db with a while loop and checking results with the in_array function http://php.net/manual/en/function.in-array.php
$availability = 0;
$cart_products = array("book", "album");
$available_products = array();
while($row = mysql_fetch_array($result)) {
$available_products[] = $row['product'];
}
foreach($cart_products as $key => $value){
if (in_array($value, $available_products)){
$availability = 1;
}
}
Yesterday another user helped out with building a generic function for handling MySQL Queries. It looks like this:
function fetchAll($query) {
$res = mysql_query($query) or trigger_error("db: ".mysql_error()." in ".$query);
$a = array();
if ($res) {
while($row = mysql_fetch_assoc($res)) {
$a[]=$row;
}
}
return $a;
}
And to output the returned results I simply do the following:
$data = fetchAll("SELECT * FROM news_table ORDER BY id LIMIT 10");
foreach ($data as $row) {
echo $row['title'];
}
My question relates to outputting the result when there's only one result in the array. Like when displaying the current blog post of a page. I want to know if I can do it without first calling the foreach loop? Is there a way to output just the first result from the array as I do not need to loop through it.
Perhaps I could have an alternate function, as opposed to the fetchAll() one above? One that just outputs one row?
Cheers,
Scott
Yes. For example:
echo $data[0]['title'];
Basically your $data is a two-dimensional array, with the first dimension being the row number (count starts with 0), so you can access any of the rows directly if you know its number. If you only have one row, it's necessarily 0.
Just count the array
if(count($data) == 1) {
// Only one dataset
} else if(count($data) > 0) {
// foreach
} else {
// no content
}
echo $data[0]['title'];
Should print exactly what your looking for. In 2D arrays the first dimension is the array index and as array index start at 0, the above code will echo the first row in that array.