Print same rows as once in php while loop - php

I have three colums which has same values for two of the rows. I want to print only one of a same row out of the two same rows using a php while loop statement. This is how the data is
ID values
1 MINI
1 MINI
2 MINI
I want to print all of these but only once with same rows based on the ID
ID Values
1 MINI
2 MINI
I can actually use DISTINCT OR GROUP BY in mysql query to find the expected answer above but I really need to use a php while statement.
This is what I have been trying my hands on
$query="SELECT * from table";
$sR=$db->query($query);
$array=array();
while($sRow=mysqli_fetch_assoc($sR)){
$ID=$searchRow['ID'];
$values=$searchRow['Values'];
$array[$ID][]=$ID;
$array2[$ID][]=$values;
}
foreach($array as $ID => $item){
$value=$array[$ID];
foreach($item as $newItem){
if($newItem===$newItem){
echo '---'.$newItem;
break;
}
}
}
This is what I am trying hands on but it doesn't seem to work as expected, I would need help on it. Thanks soo much.

When I do things like this I use a "Previous ID"-variable, in this case $PRID, to check if the ID is a duplicate. The SQL query has to be ordered by ID to make this work.
$query="SELECT * FROM table ORDER BY ID";
$sR=$db->query($query);
$array=array();
$PRID=0;
while($sRow=mysqli_fetch_assoc($sR)){
$ID=$searchRow['ID'];
$values=$searchRow['Values'];
if($ID>$PRID){
$array[$ID][]=$ID;
$array2[$ID][]=$values;
}
$PRID=$ID;
}
foreach($array as $ID => $item){
$value=$array[$ID];
foreach($item as $newItem){
if($newItem===$newItem){
echo '---'.$newItem;
break;
}
}
}

just try option 1 or option 2
$query="SELECT * FROM table ORDER BY ID";
$sR=$db->query($query);
$array = array();
// first option, expected output
// array(
// 0 => 'value',
// 1 => 'value'
// )
foreach($sR as $value) {
$array[$value['ID']] = $value['Values'];
}
var_dump($array);
$array2 = array();
// second option
foreach($sR as $value) {
$array2[$value['ID']] = array(
'ID' => $value['ID'],
'Value' => $value['Value']
);
}
var_dump($array2);
// expected output
// array(
// 0 => array(
// 'ID' => 0,
// 'Value' => 'value'
// ),
// 1 => array(
// 'ID' => 1,
// 'Value' => 'value'
// )
// )

Related

How to check if arrays values match while preserving its order in PHP

What I'm trying to do is preserve the order of an array, while determining if each of the numbers match numbers that were pulled from the database. What I have is an array of numbers ($ids), and a non empty array of rows ($rows)
$images = array();
$ids = array(
0 => '41',
1 => '42',
2 => '43',
3 => '44'
);
// database example
$rows = array(
0 => array(
'name' => 'John Doe',
'id' => '42'
),
1 => array(
'name' => 'Jane Doe',
'id' => '43'
),
);
$i = 0;
foreach ($rows as $row) {
// This works, but it doesn't preserve the order of the $ids array
if (in_array($row['id'], $ids[$i])) {
// add $id to a new array
// or use the same $id array
$images[$i]['name'] = $row['name'];
$images[$i]['id'] = $row['id'];
$i++;
}
}
Any help would be appreciated.
Since id is unique in the rows from your database, you can index the $rows array by id to make it easier to look up values there. You can do this with array_column like this:
$rows = array_column($rows, null, 'id');
Or add them to $rows using id as index as you fetch them from the db like this:
while ($row = //whatever query result/prepared statement fetch you're using) {
$rows[$row['id']] = $row;
}
Then, instead of iterating $rows, you can iterate $ids. This will ensure that the resulting $images array will be in the same order as $ids.
foreach ($ids as $id) {
if (isset($rows[$id])) {
$images[] = [
'name' => $rows[$id]['name'],
'id' => $rows[$id]['id']
];
}
}
Another thing that might make this easier (unless you're using the non-matching rows for something else), would be to use the $ids array as a parameter to a WHERE id IN clause in the query that's selecting $rows, so you won't have to do that filtering in PHP. Here's a Q&A that shows how to do that with PDO, for example: PHP - Using PDO with IN clause array.
You could iterate over ids array instead. It will be something like this:
foreach($ids as $id) {
$data = find($id, $rows);
if ($data === null) {
continue;
}
$images[] = [
'name' => $data['name'],
'id' => $data['id']
];
}
function find($id, $rows) {
foreach($rows as $row) {
if($row['id'] == $id) {
return $row;
}
}
return null;
}
Totally agree with #Don't Panic, you should fetch only the data you'll use if possible.

how do i loop through an associative array with multiple values

I just started learning php and I have this issue. I'm trying to loop through this array to get the total value of each key and output the student with the highest number. I'd really appreciate your inputs
$students = array(
'Mary' => [20,45,12],
'Grace' => [40,78,56],
'John' => [61,37,58]
);
The expected output should be Grace but i can't seem to get it to work.
You don't have to loop. Just calculate all the totals
$totals = array_map('array_sum', $students);
then output the key of the array with the maximum total.
echo array_keys($totals, max($totals))[0];
Something like this maybe assuming all grades will be positive
$students = array(
'Mary' => [20,45,12],
'Grace' => [40,78,56],
'John' => [61,37,58]
);
$highest_grade = 0;
$higest_person = "";
foreach($students as $key => $value) {
$max = max($value);
if ($highest_grade <= $max) {
$highest_grade = $max;
$highest_person = $key;
}
}
echo $highest_person . '->' . $highest_grade;
Output is using http://phptester.net/
Grace->78

Add multiple MYSQLI results as an array value in a foreach loop

I have this script that converts mysqli records into an array and i'm using a foreach loop to show those results. The problem I have is how can I show the gender value of the array_column as well in the foreach loop too?
I'm only able to show the username value only. I don't know how I can show the gender values in the foreach loop as well. Please don't suggest other loop types. I need to do this with a foreach loop with an array_column.
Here is my code example
<?php
$db_servername='localhost';
$db_username='bbb';
$db_password='1234';
$db_name='test';
$db_connect= new mysqli($db_servername,
$db_username,$db_password,
$db_name);
$db_query= "SELECT*FROM 500_users LIMIT 25";
$db_result= $db_connect->query(
$db_query);
while($db_row= $db_result->fetch_assoc()){
$items[] = $db_row;
}
$array_structure_for_items_value_id = array_column($items,'username','gender');
foreach($array_structure_for_items_value_id as $index => $value){
echo $value.'<br>';//<--username
//echo $value.'<br>';<--I will like to show the gender value as well but how?
}
?>
In the foreach loop you've set up, $index holds the 'user_id'.
echo $index . ': ' . $value
Results in:
"*user_id*: *username*"
If you have an array like this:
$heroes = [
['id' => 10,'hero' => 'superman', 'gender' => 'm'],
['id' => 21,'hero' => 'wonder woman', 'gender' => 'f'],
['id' => 34,'hero' => 'poison ivy', 'gender' => 'f'],
['id' => 46,'hero' => 'penguin', 'gender' => 'm'],
];
And you do this:
$other = array_column($heroes, 'hero', 'id');
You get this:
[
10 => 'superman',
21 => 'wonder woman',
34 => 'poison ivy',
46 => 'penguin'
]
If you iterate through this array, you can only get the index or the hero name because that is all there is in the array.
If you do this:
$other = array_column($heroes, 'hero', 'gender');
You get this:
[
'f' => 'poison ivy',
'm' => 'penguin'
]
Because the gender is used as a key and keys must be unique.
Therefore, it is your use of array_column that is getting in your way.
I don't see why you just don't iterate through your array.
You do not need array_column.
while($db_row= $db_result->fetch_assoc()){
$items[] = $db_row;
}
foreach($items as $item) {
echo $item['hero'].'<br>';
echo $item['gender'] . '<br>';
}
I'm assuming you mean how to show multiple array values in a foreach loop, if that is what you mean then this is my method of your example illustrating that with a third made up array value. Just to give you a better understanding of my example.
<?php
$db_servername='localhost';
$db_username='bbb';
$db_password='1234';
$db_name='test';
$db_connect= new mysqli($db_servername,
$db_username,$db_password,
$db_name);
$db_query= "SELECT*FROM 500_users LIMIT 25";
$db_result= $db_connect->query(
$db_query);
while($db_row= $db_result->fetch_assoc()){
$items[] = $db_row;
}
$array_1 = array_column($items,'username');
$array_2 = array_column($items,'gender');
$array_3 = array_column($items,'password');
$iterator = new MultipleIterator();
$iterator->attachIterator(new ArrayIterator($array_1));
$iterator->attachIterator(new ArrayIterator($array_2));
$iterator->attachIterator(new ArrayIterator($array_3));
foreach($iterator as $index => $value){
echo $index[0].'<br>';
echo $value[0].'<br>';
echo $index[1].'<br>';
echo $value[1].'<br>';
echo $index[2].'<br>';
echo $value[2].'<br>';
}
?>

Search associative array of arrays. How?

My question is how can I search an array built this way? Basically there may be a need to repeat the key and this is what I got so far to maybe solve this. If the price is the same for 2 different items I cannot have 2 keys with the same value.
Please feel free to improve on array layout.
$price_list = array(
1 => array("9.99", "EA_WTRESRVD"),
2 => array("9.99", "EA_WTRESRV")
);
Provided there will never be any duplication of the second column, you can do this:
$search = "EA_WTRESRVD"; //value to search for
$price_list = array(
1 => array("9.99", "EA_WTRESRVD"),
2 => array("9.99", "EA_WTRESRV")
);
$array = array_column($price_list, 0, 1);
echo $array[$search];
I would suggest that if you have a unique product code (SKU), you should use this to index your array.
$products = [
'EA_WTRESRVD' => [
'name' => '...',
'price' => 9.99,
// ...
],
'EA_WTRESRV' => [
'name' => '...',
'price' => 9.99,
// ...
],
];
Then you can access the price of any product by it's SKU.
$price = $products['EA_WTRESRV']['price'];
Here's one way:
<?php
$price_list = [ 1 => array("9.99", "EA_WTRESRVD"),
2 => array("9.99", "EA_WTRESRV")];
$search = "EA_WTRESRV";
foreach ($price_list as $arr) {
if (in_array( $search, $arr )) {
echo $search;
}
}
The foreach iterates over the multidimensional array whose elements are each arrays. Each array is inspected by in_array() for the search term.
However, this is not the only way. If you wish to avoid in_array(), you could also code as follows:
<?php
$price_list = [ 1 => array("9.99", "EA_WTRESRVD"),
2 => array("9.99", "EA_WTRESRV")];
$search = "EA_WTRESRV";
$len = strlen($search);
foreach ($price_list as $arr) {
$val = array_values($arr);
foreach($val as $v) {
if ( ( strpos( $v,$search )) !== false) {
if ( strlen($v) == $len) {
echo "$search is in the price list.\n";
}
}
}
}

How to match 2 arrays, and loop through to display an array value?

I'm trying to match two arrays, if matched then loop through array value to display them on the page.
This is how I am doing it.
$productIDs = array(
'0' => array(
'product_id' => '565355',
'product_name' => 'stackPDF',
'product_file' => 'http://www.example.com/stack.pdf',
),
'1' => array(
'product_id' => '563423',
'product_name' => 'lostPDF',
'product_file' => 'http://www.example.com/lost.pdf',
),
'3' => array(
'product_id' => '4442',
'product_name' => 'No product',
'product_file' => '',
)
);
function getProducts($productIDs){
$getIDs = explode(',', $_GET['product_id']);
$intersection = array();
foreach($productIDs as $items)
{
$intersection[] = array_intersect($items, $getIDs);
}
if(!empty($intersection)){
return $intersection;
} else {
echo "There are no products available!";
}
}
$getProducts = getProducts($productIDs);
function getDownloads($getProducts){
foreach($getProducts as $item){
print_r($item);
}
}
$getDownloads = getDownloads($getProducts);
In the getProducts() function, I'm checking to see if the product_id in the header match any of the product_id in $productIDs, to only show the available links for those that are in the header.
$getProducts variable has the available product_id that's already matched in an array, and in the $getDownloads I was trying to "If id's are available, loop through and display the product_file parameter value from the multidimensional array" but I can't seem to loop through it, rather I can't figure out how to match it/return the values.
array_filter($array, function($v) use($id){ return $v['product_id'] == $id;})
The easiest way I can think of is:
$item_exists = array_filter($productIDs, function($item) use ($check) {
return md5(json_encode($item)) == md5(json_encode($check));
});
json_encode will serialize the array to string and md5 will create a compare key, if they are equal, it will be inserted in the $item_exists array.
Edit: I was thinking of comparing product objects, but I guess you need the ID's only, you can use something like this:
$existing_values = array_filter($productIDs, function($p)use($getIDs){
return in_array($p["product_id"], $getIDs);
});

Categories