Find missing values in array - PHP [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have an array counting multiple values like D0001, D0002, D0003, ...
But sometimes a value is missing, in this case these should be the new ID. If there is no value missing then take the next one in line.
This is the code I used to retrieve an array.
example => array = array("D0001","D0002","D0003","DOOO5");
# function finding missing values?
function missing_values($list)
$range = 0;
foreach ($list as $l){
$nr = $range+1
if ($l != $nr){
$id = $nr;
}
}
$numbers = array();
while($row = $result->fetch_array()){
$id = $row['id'];
echo "--------------------------------" . "<br/>";
echo "ID " . " --> " . $id ."<br/>";
$id = substr($id,1);
echo "ID " . " --> " . $id ."<br/>";
$id = ltrim($id, '0');
echo "ID " . " --> " . $id ."<br/>";
$list[] = $id;
}
print_r($list);
# Find missing values
$array = missing_values($list);
if(empty($array)){
$max = max($list);
$id = $max+1;
}else{
$keys = array_keys($array);
$id = $array[$keys[0]];
}
Could someone tell me how I can't find the missing values in array? Or are the more easy ways to do this?

# Determine the first free id
function get_first_free_id($id_list){
// construct a new array
$new_array = range($id_list[0],max($id_list));
// use array_diff to find the missing elements
$mis_array = array_diff($new_array, $id_list);
$keys = array_keys($mis_array);
if(empty($keys)){
$highest = max($id_array);
$id = $highest+1;
}else{
$id = $mis_array[$keys[0]];
}
return $id;
}

You can do this using the bellow logic
$myArray = array("D0001","D0002","D0003","D0005", "D0009", "D0019", "D0020", "D0030");
$first = reset($myArray);
$last = end($myArray);
for ($i=$first; $i<=$last; $i++) {
$index = array_search($i, $myArray);
if(!is_numeric($index)) {
echo "missing " .$i;
echo "<br>";
}
}
http://sandbox.onlinephpfunctions.com/code/25daa236e6f02a0566dfe0ea06124776dbf20da0

Related

How to count/sum this values of the same word in PHP?

I am confused to count these words,
I've some data like this :
web = 1
sistem=1
web=1
sistem=1
web=1
sistem=1
sistem=0
sistem=0
web=0
sistem=0
web=0
sistem=0
web=0
web=0
I want to make result like this :
web = 3
sistem = 3
I'm using array_count_values(), but this result is not good
Array ( [web=1] => 3 [sistem=1] => 3 [sistem=0] => 4 [web=0] => 4 )
My code like this :
foreach ($g as $key => $kata) {
if (strpos($cleanAbstrak, $kata)) {
echo $kata . $ada . "<br>";
$p[] = $kata . "=" . $ada;
// print_r($p);
echo "<br><br>";
} else {
echo $kata, $tidak . "<br>";
$q[] = $kata . "=" . $tidak;
// $m = explode(" ", $q);
// print_r($q);
// echo $q . '<br>';
echo "<br><br>";
}
}
$s = array_merge($p, $q);
echo "<br><br>";
print_r($s);
echo "<br>";
$f = array_count_values($s);
// print_r($f);
echo "<br><br>";
thank you very much if you are willing to help me
RESULT THIS CODE
Another simple way is use a counter like that:
$web=0;
$sistem=0;
foreach ($g as $key => $kata) {
if (strpos($cleanAbstrak, $kata)) {
$sistem=$sistem + $ada;
} else {
$web=$web+$tidak
}
}
echo 'web='.$web.'<br> sistem='.$sistem;
First, you need to separate word and value.
Second, you need to check the value : if it's zero you let it go (can't hold it back anymore). Else you count the value ; if it's written, i suppose it can be greater than 1 ; if it's not, it should be "word", or nothing (which would greatly facilitate counting).
Something like
<?php
$tab = [
'web=1',
'sistem=1',
'web=1',
'sistem=1',
'web=1',
'sistem=1',
'sistem=0',
'sistem=0',
'web=0',
'sistem=0',
'web=0',
'sistem=0',
'web=0',
'web=0',
];
$tab_clean = [];
foreach($tab as $item) {
preg_match('/([a-z]+)=([\d]+)/', $item, $matches);
//print_r($matches);
$word = $matches[1];
$number = $matches[2];
for($i = 0; $i < $number; $i++) {
$tab_clean[] = $word;
}
}
$tab_count = array_count_values($tab_clean);
print_r($tab_count);
?>

PHP loop outputting duplicates

public function select(){
$rows = [];
$connection = $this->connect();
$result = $connection->query("SELECT username FROM users");
while ($row = $result->fetch_assoc()){
$rows[] = $row;
}
$userlist = 0;
foreach($rows as $username){
$userlist .= $username['username'];
}
$get_rankings = [1,2,3,4];
$get_image_path = "images/";
$total = 0;
for ($x = 0; $x < count($get_rankings); $x++){
$total = $get_rankings[$x];
$path .= "<img src = '" . $get_image_path . $total . ".png'>\n" . $userlist . "<br/>";
// echo "<span class = 'align-down'>{$path}";
// echo "<p class = 'user-name'> {$rows['0']}</p>";
// echo "</span>";
}
echo $path;
}
I'm trying to output a simple ranking but using the number index as images to display them.
In the past i've tried to do something similar but couldn't figure out how to match player it with images on the side.
The output im getting is this:
It's outputting each entry 4 times(I get why, its in a loop) but I can't figure out the correct solution to write it outside of a loop or properly
The desired output is:
My DataBase reads as:
[id][username][password]
If there is an easier solution, i'm all ears. I don't know how to approach this.
There's no need for $userlist. Output the username from $rows[$x].
$path = "";
$max = min(count($rows), count($get_rankings));
for ($x = 0; $x < $max; $x++){
$total = $get_rankings[$x];
$path .= "<img src = '" . $get_image_path . $total . ".png'>\n" . $rows[$x]['username'] . "<br/>";
// echo "<span class = 'align-down'>{$path}";
// echo "<p class = 'user-name'> {$rows['0']}</p>";
// echo "</span>";
}

Why is my for loop displaying the same item twice?

I am trying to display each item in a JSON array of reviews. There are two reviews in the array, but instead of displaying both of them, this code displays same one twice.
Why is this happening?
$response = curl_exec($curl);
$data = json_decode($response, true);
// Setup the Review for posting to the Mysql Database
// Loop through Reviews
for ($i=0; $i<count($data['reviews']); $i++) {
$id = $data['reviews']['0']['id']; // good
$stars = $data['reviews']['0']['stars']; //good
$title = $data['reviews']['0']['title'];
$text = $data['reviews']['0']['text'];
$createdAt = $data['reviews']['0']['createdAt'];
$companyReply = $data['reviews']['0']['companyReply']['text'];
$companyReplyDate = $data['reviews']['0']['companyReply']['createdAt'];
// Do Mysql insert for each row
// show this
echo "id: " . $id . "</br>";
echo "stars: " . $stars . "</br>";
echo "title: " . $title . "</br>";
echo "text: " . $text . "</br>";
echo "Created: " . $createdAt . "</br>";
echo "Reply: " . $companyReply . "</br>";
echo "Reply Date: " . $companyReplyDate . "</br> </br>";
}
curl_close($curl);
It is because you aren't actually using your loop increment variable to get different array keys. You're just selecting the ['0'] index repeatedly. Instead, use $i as the array key like this:
for ($i=0; $i<count($data['reviews']); $i++) {
$id = $data['reviews'][$i]['id']; // good
$stars = $data['reviews'][$i]['stars']; //good
$title = $data['reviews'][$i]['title'];
$text = $data['reviews'][$i]['text'];
$createdAt = $data['reviews'][$i]['createdAt'];
$companyReply = $data['reviews'][$i]['companyReply']['text'];
$companyReplyDate = $data['reviews'][$i]['companyReply']['createdAt'];
// ... etc.

Iterating array/hashmap

Edit: Nico Parodi's answer is correct. I will eventually return to finding out why, but for now I will just take it as it is and hope nothing else fails.
I have a table with three fields: "date", "name", "location". I want to group all the records selected from this table based on their date.
By copy-pasting some code from php mysql group by date with yyyy-mm-dd format, I've managed to get this array, date -> name:
$result = mysqli_query($con,"SELECT date, name, location FROM events");
while($row = mysqli_fetch_array($result)) {
$foo[$row['date']][]=$row['name'];
}
Everything's great, I can iterate it without issues. Now I want to store all the row columns as a value for the date key, so I try to store the entire row as a value:
$result = mysqli_query($con,"SELECT date, name, location FROM events");
while($row = mysqli_fetch_array($result)) {
$foo[$row['date']][]=$row;
}
And now I can't iterate it. count($rowCol) seems to give me the nr of columns in all the array for either keys, not just for one. How can I iterate it?
foreach($foo as $date => $events) {
echo $date . ": "; // this is okay
foreach($events as $key => $rowCol){
for ($i = 0; $i<count($rowCol); $i++) {
echo $rowCol[$i] . " ";
}
}
}
for ($i = 0; $i<count($rowCol); $i++) {
echo $rowCol[$i] . " ";
}
$rowCol has the double of fields that you expect as mysqli_fetch_array() fetches as both associative and numeric array.
So,
for ($i = 0; $i<(count($rowCol)/2); $i++) {
echo $rowCol[$i] . " ";
}
should work.
Replace :
for ($i = 0; $i<count($rowCol); $i++) {
echo $rowCol[$i] . " ";
}
By
foreach($rowCol as $k =>$v) {
echo $v . " ";
}
for ($i = 0; $i<count($rowCol); $i++) {
echo $rowCol[$i] . " ";
}
this part of code doesn't work because rowCol is an associative array + numeric array. Try to replace mysqli_fetch_array with mysqli_fetch_row
Can you tell us what's the output of this code? (show plain text, no HTML):
foreach($foo as $date => $event) {
echo $date . ": ";
foreach($event as $key => $value){
print_r($value);
}
echo "\n";
}
Original answer:
$events contains a single event, your code should look more like this:
foreach($foo as $date => $event) {
echo $date . ": ";
foreach($event as $key => $value){
echo $value . " ";
}
echo "\n";
}

How to use mysql to find a field name of a record?

PDO sql codes :
while($r = $q->fetch(PDO::FETCH_ASSOC)){
$gg = join('</td><td>', $r);
echo "<tr><td>" . $no_count . "</td><td>" . $gg . "</td></tr>";
$no_count = $no_count + 1;
}
variable $r is the record, how can I echo the field name of $r?
Let's say $r carry records from 2 different fields "product" and "price". The value of $r is "apple", "130". How can I add "usd" into "130"?
I need something like.... if $field_name == "$r['price']" { $r = join('usd', $r); };
Thanks to Mike B, I almost there :
while($r = $q->fetch(PDO::FETCH_ASSOC)){
foreach ($r as $name => $value) {
if ($name == "price"){
$r = "usd" . $value; // this line got problem, how to change the value in an array variable $r?
}
}
$gg = join('</td><td>', $r);
echo "<tr><td>" . $no_count . "</td><td>" . $gg . "</td></tr>";
$no_count = $no_count + 1;
}
array_keys($r) will get you a list of fields from the table since you're fetching an associative array.
You can also loop through $r:
foreach ($r as $name => $value) {
print "$name: " . $value;
}
Update
// this line got problem, how to change the value in an array variable $r?
$r[$name] = 'usd' . $value;
Make the edit to the original name. Since you have the key in the $name variable from the foreach loop you can set it directly.

Categories