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;
});
Related
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.
I'm currently trying to use a foreach to return all the addresses using the relation from my event model. All is fine, returns all the addresses but will return even the duplicate results. I tried the array_unique but not sure I have the syntax correct.
<?php
foreach ($data->events as $address) {
//array_unique($address, SORT_REGULAR);
echo $address->getAddressString() ."<br/> <br/>";
}
?>
You should try with array store technique using array_unique
// First Store data in $arr
$arr = array();
foreach ($data->events as $address) {
$arr[] = $address->getAddressString();
}
$unique_data = array_unique($arr);
// now use foreach loop on unique data
foreach($unique_data as $val) {
echo $val;;
}
You can add each unique element to a new array and then see if they exist with in_array():
$uniques = [];
foreach($data->events as $address){
if(!in_array($address->getAddressString(), $uniques)){
$uniques[] = $address->getAddressString();
echo $address->getAddressString()."<br><br>";
}
}
There's a faster way, if you'd like to prematurely optimize.
<?php
$arr = array();
foreach ($data->events as $address) {
$arr[$address->getAddressString()] = 'a'; // value doesn't matter
// using inherent uniqueness of keys.
}
// $addrs = array_keys($arr);
// optionally, take all those array keys and put them in values.
// keys would become regular numeric keys
?>
That should run faster than any of the other answers here. But it will only make a difference if you are dealing with large amounts of data.
If you want to echo, you will want to do array_keys if you didn't above. Here it is in one line:
echo implode(', ',array_keys($arr)); // comma separated list of unique values
Or this, for sorted:
$addrs = array_keys($arr);
sort($addrs);
echo implode(', ',$addrs); // sorted list
Finally, I'd like to add that you should be getting unique, ordered results from your data model in the first place. The database is much faster and better at simple tasks like ordering unique results than your PHP code ever will be.
SELECT DISTINCT `address` FROM `table`
WHERE `city` LIKE 'Lodi'
ORDER BY 'address' ASC
array_unique should do it. Try this:
<?php
foreach (array_unique($data->events) as $address) {
echo $address->getAddressString() ."<br/> <br/>";
}
?>
You can try this -
<?php
$all_addresses= array();
foreach ($data->events as $address) {
$all_addresses[]= $address->getAddressString();
}
$all_addresses= array_unique($all_addresses);
foreach($all_addresses as $val) {
echo $val . "<br/> <br/>";
}
?>
Or
Instead of
foreach($all_addresses as $val) {
echo $val . "<br/> <br/>";
}
Do
echo implode('<br/> <br/>', $all_addresses);
Even though the question was different I agree with Steve. You should adjust your query. Its faster, more readable and maintainable. You don't want to do anything you don't need to do.
If i gathered correctly you have to tables that are in relation. Great. Try something like this:
$var1 = YourModel::model()
->with('address_table')
->findAllByAttributes(array(-optional if you want certain columns-),
array('condition'=>'`type` LIKE :type AND `typeId` = :typeId AND `suggestionId` IS NULL', 'params'=>array(':type'=>$_GET['type'], ':typeId'=>$_GET['typeId']), 'group'=>'address_table.`column`'));
Most important thing here for you is the 'group' command which like the name says groups results and returns only unique ones. Be sure to prefix it correctly, either table name or alias depending on what you are working with.
Hope it helps.
I'm trying to show the max value of column teams from mysql. Above the while loop I've selected teams from my mysql table and then as you can see in my code below I have included max($teams) - but it is returning an error? Where am I going wrong.
while ($rows = mysql_fetch_assoc($result)) {
$teams = $rows['teams'];
if($teams > "1") {
echo '<div class="bestbettor">'.'<span class="redtext">'."Bettor: ".'</span>'. $rows['username'].'</div>';
echo '<div class="bestbettor">'.'<span class="redtext">'." Bet: ".'</span>'.max($teams). " team accumulator".'</span>'.'</div>';
}
}
you must pass an array to max().
$teams = $rows['teams']; // saves as string.
if your teams were delimited by a comma then you could do something like:
$teams = explode(",",$rows['teams']); // saves as array
then you could do max()
If one parameter is given to max() it has to be an array of values of which max() will return the highest value in that array. It seems like you've just given it a single string.
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.
Sorry for the incredibly newbie question, but I can see myself drifting into bad practices if I don't ask.
I have a PHP method that I want to return all the values of a given database column, in order to place the contents in a dropdown menu for a HTML form. I could obviously construct the whole HTML in the PHP method and return that as a string, but I imagine this is pretty bad practice.
Since PHP methods can only return one value, I imagine I'll need to call the method several times to populate the dropdown menu, or pass an array from the method.
What would be a good solution to this (presumably) common problem? Thanks.
Well, an array is one value, containing tons of other values. So just have your method return a array of results.
edit: as Hammerstein points out you could use objects but its as good/bad as arrays depending on context. Very similar.
You could use an object as your return type. So;
class MyReturnValue
{
public $Value1;
public $Value2;
}
function getMyValues()
{
$results = GetDatabaseValues( ); // Assume this returns an associative array
$result = new MyReturnValue();
$result.Value1 = $results["Value1"];
$result.Value2 = $results["Value2"];
}
Then in your code, you can refer to $result.Value1 etc.
There is no PHP function to do this, so you will have to form an array from the results.
$column = array()
$query = mysql_query("SELECT * FROM table ORDER BY id ASC");
while($row = mysql_fetch_array($query)){
$column[] = $row[$key]
}
Then pass $column to your view(HTML)
foreach($column as $value)
{
echo "<li>" . $value . "</li>";
}
You can have arrays in arrays, so if you have a table with several columns you could assign them to an array as separate arrays:
$all_results = array();
foreach($rowInDatabase as $key => $value){
// each row will be an array with a key of column name and value of column content depending how you get the data from the DB.
$colname = $key;
$colVal = $value; //this is an array
$all_results[$colname] = $colVal; //append the current row to the array
}
}
code like this will populate your array with an array per row of the table so if there are ten rows and five columns you could get row 2 column 3 with $all_results[1][2]; (as they start from 0).
Not quite sure I understand what you want to do fully, but you could always pass the result back from the method, and then loop through it in your HTML.
Your method would be something like:
public function my_method()
{
$result = $db->query($sql_here);
return $result;
}
And then your HTML would be
<select>
<?
$result = $class->my_method();
while($row = $result->fetch_assoc())
{
echo '<option>'.$row['some_col'].'</option>';
}
?>
</select>