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.
Related
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;
});
I'm fairly new to php, and I don't know how to work with arrays very well. Here's the deal, I want to add into a multidimensional array three or more values I obtain from my database, then I want to sort them based on the timestamp (one of the values). After that, I want to show all of the sorted values. I can't seem to do this, here's the code
$queryWaitingPatients = 'SELECT ArrivalTime, TargetTime, Order, Classification FROM exams WHERE (CurrentState = "Pending")';
$results = mysql_query($queryWaitingPatients) or die(mysql_error());
if (mysql_num_rows($results) == 0) {
echo '<p>There\'s currently no patient on the waiting list.</p>';
return;
}
while ($rows = mysql_fetch_array($results)) {
extract($rows);
//now is the part that I don't know, putting the values into an array
}
// I'm also not sure how to sort this according to my $TargetTime
asort($sortedTimes);
//the other part I don't know, showing the values,
Thanks for the help!
Well, let's look at your code. First, you have a query that's returning a result set. I don't recommend using mysql_fetch_array because it's not only deprecated (use mysqli functions instead) but it tends to lend itself to bad code. It's hard to figure out what you're referencing when all your keys are numbers. So I recommend mysqli_fetch_assoc (be sure you're fully switched to the mysqli functions first, like mysql_connect and mysqli_query)
Second, I really dislike using extract. We need to work with the array directly. Here's how we do this
$myarray = array();
while ($rows = mysqlI_fetch_assoc($results)) {
$myarray[] = $rows;
}
echo $myarray[0]['ArrivalTime'];
So let's go over this. First, we're building an array of arrays. So we initialize our overall array. Then we want to push the rows onto this array. That's what $myarray[] does. Finally, the array we're pushing is associative, meaning all the keys of the row match up with the field names of your query.
Now, the sorting really needs to be done in your query. So let's tweak your query
$queryWaitingPatients = 'SELECT ArrivalTime, TargetTime, `Order`, Classification
FROM exams
WHERE CurrentState = "Pending"
ORDER BY TargetTime';
This way, when your PHP runs, your database now churns them out in the correct order for your array. No sorting code needed.
$arr = array();
while ($rows = mysql_fetch_array($results)) {
array_push ($arr, $row);
}
print_r($arr);
<?php
$queryWaitingPatients = ' SELECT ArrivalTime, TargetTime, Order, Classification, CurrentState
FROM exams
WHERE CurrentState = "Pending"
ORDER BY TargetTime ';
$results = mysql_query($queryWaitingPatients) or die(mysql_error());
if ($results -> num_rows < 1)
{
echo '<p>There\'s currently no patient on the waiting list.</p>';
}
else
{
while ($rows = mysqli_fetch_array($results))
{
$arrivaltime = $row['ArrivalTime'];
$targettime = $row['targettime'];
$order = $row['Order'];
$classification = $row['Classification'];
echo "Arrival: ".$arrivaltime."--Target time: ".$targettime."--Order: ".$order."--Classification: ".$classification;
}
}
echo "Done!";
//or you could put it in a json array and pass it to client side.
?>
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>
I am looking to store the database values which are already stored as id's and retrieve via a for each loop within an array.
I have tried something like this, but it is not working:
foreach ($list as $item)
{
$commaSeparated = implode(',' , $item['id');
}
echo $commaSeparated;
Where item['id'] is the specific column pulled out of the query. If I use the $list variable, then I am getting the full result of the query which I do not want.
But, my error results in this:
Warning: implode(): Invalid arguments passed
This is what has correctly returned what I need:
foreach ($list as &$id)
{
$listArr[] = $id['toolbar_id'];
$commaSeparated = implode(',' , $listArr)
echo $commaSeparated;
That happens because you need to perform
$commaSeparated = implode(',' , $list);
It is not a good practice though. You should never store the lists as comma-separated items in database. Instead - create additional table for it and store 1 item per row.
The second argument to implode needs to be an array. Try this:
$commaSeparated = implode(',', $list);
Implode function accepts a separator and an array for parameters. Then you should do this:
$commaSeparated = implode(',' , $list);
echo $commaSeparated;
(Source: http://php.net/manual/pt_BR/function.implode.php)
You need to do more checks to avoid the error if your data is not in correct format.
if(is_array($list)){
foreach ($list as $item)
{
if(is_array($item))
$commaSeparated = implode(',' , $item);
}
echo $commaSeparated;
}
I suggest you trying a var_dump($variable) where $variable is the ...variable, in which the data is stored, knowing its structure will tell you what data to expect and how to iterate over it.
foreach($sql_result['record2'] as $key ){
echo $key['ENO'];
}
when iam doing foreach loop for the above statement .It outputs (10,9,2,8,4).I need it to sort to (2,4,8,9,10)
one more thing is "$key" is of Type Array.when i do like this array_multisort($key['ENO']). how do i acheive this
$vals = array();
foreach($sql_result['record2'] as $key ){
$vals[] = $key['ENO']
}
sort($vals);
or if you want to pre-sort the values you could use usort()
Untested Code, but something like the following should work....
$tmpArray = array();
foreach ($sql_result['record2'] as $key => $value) {
array_push($tmpArray, $value['ENO']);
}
array_multisort($tmpArray, SORT_DESC);
At this point, $tmpArray will be your sorted array of values. OR, you can just do an ORDER BY clause in your SQL, in which case the result set will be ordered by the values you want.
You don't need to sort the array, you can simply append an "ORDER by ENO" to your SQL query to return an ordered result.