I have this code and I want to compare the data that came from db with the one user selects but it seems that the foreach($question_answers as $answer){
and foreach ($user_answer as $key => $value) { it is not good it is repeating for 4 times more, I need a way to compare $user_answer which is what user has selected request from the view, and the $answer['order'] the order comes from database. So I need a loop or something to compare these two.. any help..? thank you.
foreach($questions as $question) {
$question_answers = OrderingAnswer::where('question_id', $question->id)
->where('deleted',0)
->get()
->toArray();
$users_answers = $request->except('_token', 'test_id');
$user_answer = $users_answers[ $question->id];
// $user_answer ---> Array ( [0] => 1 [1] => 4 [2] => 3 [3] => 2 )
foreach ($question_answers as $answer) {
//$answer['order'] ---> 1
foreach ($user_answer as $key => $value) {
if ($answer['order'] == $value ) {
echo "ok ===>" .$value . "<br>" ;
} else {
echo "no -------------------------------- >".$value . "<br>" ;
}
}
}
I have tried this - it is working perfect. (This question was really intresting)
Here basically i am comparing multidimensional array value to a single dimensional array value. it will just give you array of matched results.
<?php
$question_answers= array(
array("id"=>251,'question_id'=>242,'order'=>1),
array("id"=>252,'question_id'=>243,'order'=>2)
);
$user_answers = array(1,4,3,2);
// you can just use this part
$question_answers = array_filter($question_answers, function($arr) use ($user_answers) {
return in_array($arr['order'], $user_answers);
});
echo "<pre>";
print_r($question_answers);
?>
Related
I'm trying to add an <hr> tag between lines when a new name is encountered.
$conn = new mysqli("localhost", "root", "", "test");
$rs = $conn->query("SELECT * FROM usuarios");
$info = [];
$i = 0;
while($rows = $rs->fetch_array()) {
$info[$i]["pass"] = $rows["pass"];
$info[$i]["name"] = $rows["name_real"];
$i++;
}
// I want to print a line just after the last duplicated value
for($i = 0; $i < count($info) - 1; $i++) {
if($info[$i]["name"] !== $info[$i +1]["name"] && // some duplicate condition) {
$info[$i]["line"] = "<hr>";
};
}
This is the structure of my info array build from the resultset.
Array
(
[0] => Array
(
[pass] => 12
[name] => Martin
)
[1] => Array
(
[pass] => 20
[name] => Martin
)
[2] => Array
(
[pass] => 2
[name] => Martin
)
[3] => Array
(
[pass] => 2
[name] => Alberto
)
)
My desired result would be something like:
<p>Martin<p>
<p>Martin<p>
<p>Martin<p>
<hr>
<p>Alberto<p>
If you don't care what the duplicate names are or how many duplicates exist, and you just want to see whether or not there are any, it looks like it could be simpler code than some of the possible duplicate answers.
Get the names
$names = array_column($array, 'name');
Then check if the full list of names is equal to the unique list.
$has_duplicates = $names != array_unique($names);
Disclaimer: This answer looks odd now. It was provided for Revision 1 of the question. I seem to have misunderstood the question somewhat, and then Revision 2 transformed it to the extent that this answer no longer applies at all. Still, I think it's a useful way to do the thing that it seemed was trying to be done at first.
This solution would be handy:
$result = array();
$names = array_count_values(array_column($source, 'name'));
foreach($names as $key=>$val) {
$result[$key] = ($val == 1 ? false : true);
}
This can be achieved with just one loop. First, use your mysqli query to order the resultset by name_real. (If you are only going to use name_real, you can change the SELECT clause to reflect this. I have shown this in the commented query.) Then write a condition that checks for a new/unique name_real -- if so, echo <hr>.
Code: (Demo)
//$rs = $conn->query("SELECT `name_real` FROM usuarios ORDER BY `name_real`;");
$rs=[
['pass'=>2,'name_real'=>'Alberto'],
['pass'=>12,'name_real'=>'Martin'],
['pass'=>20,'name_real'=>'Martin'],
['pass'=>2,'name_real'=>'Martin']
];
$prev=NULL;
//while($rows = $rs->fetch_array()) {
foreach($rs as $rows){
if($prev && $rows['name_real']!=$prev){ // if not first iteration, and new name_real
echo "<hr>";
}
echo "<p>{$rows['name_real']}</p>";
$prev=$rows['name_real']; // preserve this value for next iteration's check
}
Output:
<p>Alberto</p>
<hr>
<p>Martin</p>
<p>Martin</p>
<p>Martin</p>
The main goal of this algorithm is to find similar titles of news articles from different sources of web and group them, let's say above 55.55% similarity.
My current approach of the algorithm consist of following steps:
Feed data from MYSQL database into a two-dimensional array ex. $arrayOne.
Make another copy of that array into ex. $arrayTwo.
Create a clean array which will only contain similar titles and other content ex. $array_smlr.
Loop, foreach $arrayOne article_title check for similarity with $arrayTwo article_title
If similarity of between two titles is above 55% and if the article is not from the same news source (this way I don't check same articles from the same source) add it to $array_smlr
Sort the $array_smlr based on percentages of similarity, this way I end up grouping titles that are similar.
Below is my code for the above tasks mentioned.
$result = mysqli_query($conn,"SELECT id_articles,article_img,article_title,LEFT(article_content , 200),psource, date_fetched FROM project.articles WHERE " . rtrim($values,' or') . " ORDER BY date_fetched DESC LIMIT 70");
$arrayOne=array();
$arrayTwo=array();
while($row = mysqli_fetch_assoc($result)){
$arrayOne[] = $row;
}
$arrayTwo = $arrayOne;
$array_smlr=array();
foreach ($arrayOne as $rowOne) {
foreach($arrayTwo as $rowTwo){
$compare = similar_text($rowOne['article_title'], $rowTwo['article_title'], $p);
if ( round($p,2) >= 55.50 and $rowOne['psource'] != $rowTwo['psource'] ){
$data = array('percentage' => round($p,2), 'article_title' => $rowTwo['article_title'], 'psource' => $rowTwo['psource'], 'id_articles' => $rowTwo['id_articles'], 'date_fetched' =>$rowTwo['date_fetched']);
$array_smlr[]=$data;
}
}
}
array_multisort($array_smlr);
foreach($array_smlr as $row3){
echo $row3['percentage'] . $row3['article_title'] . $row3['psource'] . $row3['id_articles'] . $row3['date_fetched'] . "<br><br>";
}
This would work with limited functionality, only if I had two similar titles, but let's say if I had 3 similar titles, it would include duplicated rows of data in $array_smlr.
I would appreciate if you have any suggestions on optimization of this algorithm in order to improve the performance.
Thanks,
You don't really need 2 arrays instead of the foreach loop without $key wildcard you can use it with $key and skip the solver when the $key is the same. Then you also avoid dupes.
foreach ($arrayOne as $key => $rowOne) {
foreach($arrayOne as $ikey => $rowTwo){
if ($ikey != $key) {
$compare = similar_text($rowOne['article_title'],$rowTwo['article_title'], $p);
if ( round($p,2) >= 55.50 and $rowOne['psource'] != $rowTwo['psource'] ){
$data = array('percentage' => round($p,2), 'article_title' => $rowTwo['article_title'], 'psource' => $rowTwo['psource'], 'id_articles' => $rowTwo['id_articles'], 'date_fetched' =>$rowTwo['date_fetched']);
$array_smlr[$rowTwo['id_articles']]=$data;
}
}
}
i am trying to grab all records from mongodb using php.
i have two collections. question is, in practice will i be able to make a simple sentence such as for each record on the database? :
ie: john[from names collection] lives in city[from city collection] who
drives[from car collection].
Is this the correct coding for the above? I am still a newbie trying to learn step by step
<?php foreach ($details as $doc) {
echo $doc['name'] . ' lives in'; }
foreach ($place as $city) {
echo $city['name'] . ' who drives a '; }
foreach ($car as $ride) {
echo $ride['name'];
echo '<br>'} ?>
your thoughts are welcome
I expect this to be used with, say, a user_id of sorts. Doing a full table scan of this would be a really bad idea.
Here is what you can do providing you have the user_id:
$users = $mongo->users->find(['_id' => ['$in' => [1,2,3,4,5,6,7,8,9]]]);
// Set some variables which will help us perform the detail queries
$cityIds = [];
$rideIds = [];
$userResults = [];
$cityResults = [];
$rideResults = [];
// Iterate through our users.
foreach($users as $_id => $user){
// We store the MongoId for use in queries
$cityIds[] = $user['city_id'];
$rideIds[] = $user['ride_id'];
// We then store the user result itself so we don't
// Do this query multiple times.
$userResults[$_id] = $user;
}
// Now, let's get our first details.
$cityResults = iterator_to_array(
$mongo->cities->find(['_id' => ['$in' => $cityIds]])
);
// And our ride details
$rideResults = iterator_to_array(
$mongo->rides->find(['_id' => ['$in' => $rideIds]])
);
// Now let's loop and echo
foreach($userResults as $k => $user){
echo $user['name'] .
' lives in ' .
$cityResults[$user['city_id']]['name'] .
' who drives a ' .
$rideResults[$user['ride_id']]['name'];
}
Something like that would do the trick.
Here I assume that your user schema has a city and ride ID in it respectively and that the two ID fields store an ObjectId (_id) of a city and ride row; this seems to be the most logical schema.
Nest the for loops inside of each other.
<?php
foreach ($details as $doc) {
foreach ($place as $city) {
foreach ($car as $ride) {
echo $doc['name'] . ' lives in '.$city['name'].' who drives a '.$ride['name'].'<br/>';
}
}
}
?>
Thats how i do it when im trying to access data in multiple collections to form the output
I'm trying to get some specific keys and values from the database. My database entries look like so:
id | name | description | value
------------------------------------------
1 | lang | default language | en
2 | date | date format | YYYY-MM-DD
I want to echo only my name and value fields. I've tried using a nested foreach loop, like so:
foreach($details as $key => $value)
{
foreach($value as $index => $row)
{
echo $index . " / " . $row . "<br />";
}
echo "<br />";
}
But that only echos:
id / 1
name / lang
description / default language
value / en
id / 2
name / date
description / date format
value / YYYY-MM-DD
However, when I add an offset, like so: $index[1], I get this like a instead of name, or e instead of description.
I've previously worked from while loops using mysql_fetch_array, but this would give me a repeated element (say a <tr>) whereas I simply need to extract the value of the field because this will be used to build a form for the user to manage.
Would anyone have a suggestion or different approach for me to do something of the sort ?
EDIT
The query comes from a class file:
// extracted from my queries.class.php
public function my_prefs()
{
global $db;
$query = "SELECT * FROM preferences WHERE value!=NULL";
return $db->select($query);
}
// extracted from the source file
$module_details = $query->my_prefs();
EDIT #2
Perhaps this will help you understand my needs:
foreach($module_details as $key => $value)
{
print_r($module_details);
}
returns:
Array
(
[0] => stdClass Object
(
[id] => 1
[name] => lang
[description] => default language
[value] => en
)
[1] => stdClass Object
(
[id] => 1
[name] => date
[description] => date format
[value] => YYYY-MM-DD
)
}
I need to access only lang / en and date / YYYY-MM-DD.
Sounds like you're looking for something like this:
$tmp = array();
foreach($details as $key => $value)
{
// "name" => "value" dictionary later access
$tmp[$value["name"]] = $value["value"];
echo $value["name"] . " = " . $value["name"]; // echos e.q. "date = YYYY-MM-DD"
echo "<br/>";
}
echo $tmp["date"]; // echos e.q. "YYYY-MM-DD"
Perhaps I misunderstood the question..
But I believe you are trying to access the specific column entry from the array. You can do this by using the keys you are outputting instead of using a numeric index.
foreach($details as $key => $value)
{
echo $value['name'];
echo $value['value'];
echo "<br />";
}
EDIT
If you want to limit the results from your query so you only have the fields you requested replace:
$query = "SELECT * FROM preferences WHERE value!=NULL";
with
$query = "SELECT name, value FROM preferences WHERE value!=NULL";
Finally got around to getting something to work. Here's what I did:
foreach($details as $row)
{
$name = $row->name;
$value = $row->value;
// In order to specify for checkboxes, select, radio, etc.
if($name == "lang")
{
// different info depending on the value
}
else
{
// do something generic here
}
}
Might not be an optimal option, but this works like I need it to work.
Due to working with a restricted working environment, I need to put half of this array into one table row and another half into another .
This is the array (already sorted in order of what I need):
Array
(
[product] => KFE-1221
[description] => Classic Blue
[current_stock] => 630
[purchase_order] =>
[total_sales] => 0
[avail_to_sell] => 630
[size_run1] => 15
[size_run2] => 62
[size_run3] => 122
[size_run4] => 113
[size_run5] => 102
[size_run6] => 92
[size_run7] => 63
[size_run8] => 61
[size_run9] => 0
[size_run10] => 0
)
I need to split the array at "size_run1" - "size_run10" into a separate table row.
Previously, I had this to display the array into a table (standard foreach) when I didn't need the size_run. Due to request I am adding it in. (And yes I am using deprecated php)
<?php
while($data = mssql_fetch_assoc($result_ats)) {
if ($data['avail_to_sell'] <= 0){
echo '<tr class="error">';
}
else {
echo '<tr>';
}
foreach($data as $k => $v){
echo '<td>'.$v.'</td>';
echo '</tr>';
}
}
?>
The reason I want to keep it as one array is because I am using one query for all the information, and with the huge database that I'm working with, it makes more sense for me to split this up on template side rather than have separate arrays and add a process of matching the product to the size_run.
What is the best way of doing this without having the split the array up into different arrays?
My desired output, which is to split up array '$v' into two separate tables like below:
<tr>
<th>product</th>
<th>description</th>
<th>current_stock</th>
<th>purchase_order</th>
<th>total_sales</th>
<th>avail_to_sell</th>
</tr>
<tr>
<th>size_run1</th>
<th>size_run2</th>
<th>size_run3</th>
<th>size_run4</th>
<th>size_run5</th>
<th>size_run6</th>
<th>size_run7</th>
<th>size_run8</th>
<th>size_run9</th>
<th>size_run10</th>
</tr>
Something like this:
$firstRow = array('product', 'description', 'current_stock', 'purchase_order', ... );
$secondRow = array('size_run1', 'size_run2', 'size_run3', ... );
while($data = mssql_fetch_assoc($result_ats)) {
echo '<tr>';
foreach($firstRow as $key){
echo '<td>' . $data[$key] . '</td>';
}
echo '</tr>';
echo '<tr>';
foreach($secondRow as $key){
echo '<td>' . $data[$key] . '</td>';
}
echo '</tr>';
}
Still maintainable if you want to change the keys.
I would still make a new array and then destroy it if you don't need it.
$newArray = array();
foreach($array as $key=>$value){
$pos = strpos($key, "size_run");
if($pos!==false){
$newArray[$key] = $value;
}
}