How to group array and mount select - php

I really need your help! How can I do to group the array results and assemble select.
Database
Image Database
PHP
<?php
$rsPA = $mysqli->query("SELECT * FROM provas_agendadas WHERE status = 'A' ");
foreach ($rsPA as $key => $rsRowPA){
$dis1[] = explode("," , $rsRowPA['disciplinas']);
}
echo '<pre>';print_r($dis1);echo '</pre>';
?>
Result:
Array
(
[0] => Array
(
[0] => EJA-1
)
[1] => Array
(
[0] => EJA-1
[1] => EJA-5
[2] => TTI-1
)
)
Expilando: From the result of the array, I will only get the number after the -, Ex: EJA-1, I only need 1, which is the ID of the discipline table.
End result you would like
Image select
I thank everyone who can help me.

You could perform an additional for loop, and explode each element on - and take the last part:
<?php
$rsPA = $mysqli->query("SELECT * FROM provas_agendadas WHERE status = 'A' ");
foreach ($rsPA as $key => $rsRowPA){
$temp = explode("," , $rsRowPA['disciplinas']);
foreach($temp as $elem){
$number = explode('-',$elem);
$number = end($number);
$numbers[] = $number;
}
}
$dis1 = array_count_values($numbers);
echo '<pre>';print_r($dis1);echo '</pre>';
?>

Related

displaying items in array ordered by id inside string

I want to display items in an array separately, ordered by groups.
The items are stored in a string like this:
$itemsString = "1:asd, 1:wer, 2:dfg, 3:gfg, 3:sdfss"; //and so forth
Then I display them like this:
$itemsArray = explode(", ", $itemsString);
foreach($itemsArray as $item){
echo substr($item,2); //substr to get rid of the group id
}
EDIT: solution
if(strpos($item, "1:")!==false){
echo substr($item,2);
}
You could perform another explode on your initial array on the colon, seperate the number and the value, then feed them into a array using the number as the key, eg:
$itemsString = "1:asd, 1:wer, 2:dfg, 3:gfg, 3:sdfss"; //and so forth
$sorted_array = [];
$itemsArray = explode(", ", $itemsString);
foreach($itemsArray as $item) {
$subItemsArray = explode(":", $item);
$sorted_array[$subItemsArray[0]][] = $subItemsArray[1];
}
print_r($sorted_array);
Which would mean $sorted_array would be pre-sorted for you (or easily sortable with ksort()):
Array
(
[1] => Array
(
[0] => asd
[1] => wer
)
[2] => Array
(
[0] => dfg
)
[3] => Array
(
[0] => gfg
[1] => sdfss
)
)
you can display them like this
$itemsArray = explode(", ", $itemsString);
foreach($itemsArray as $item){
if(strpos($item, "1:") || strpos($item, "1:") ===0 ){
echo substr($item,2)
;}
}

PHP - Delete all duplicates in array

How can I delete duplicates from multiple arrays?
pinky and cocos are double in my array. All words which are double, must be removed. If those are removed, I will put these words in my select.
I get those words from my database.
The query:
$queryClient = " SELECT DISTINCT `clients` FROM `reps` WHERE `clients` != ''";
This is my code:
while($row = mysql_fetch_assoc($resultClient)){
$names = explode(",", $row['clients']);
echo '<pre>'; print_r($names); echo '</pre>';
}
Result: (Those food words are just an example)
Array
(
[0] => chocolate
)
Array
(
[0] => vanilla
[0] => cocos
)
Array
(
[0] => strawberry
)
Array
(
[0] => pinky
[1] => watermelon
[2] => melon
[3] => cocos
)
Array
(
[0] => pinky
)
Array
(
[0] => dark-chocolate
)
I tried this in my while loop but it did not work:
$array = array_unique($names, SORT_REGULAR);
How can I remove all duplicates? Can you help me or do you have a solution for my problem? Help.
Here's a one-liner:
print_r(array_unique(call_user_func_array('array_merge', $names)));
First merge all subarrays into one, then get unique values.
Full example:
$names = array();
while($row = mysql_fetch_assoc($resultClient)){
$names[] = explode(",", $row['clients']);
}
print_r(array_unique(call_user_func_array('array_merge', $names)));
You can just do a little trick:
Flatten, count and then remove all except the last.
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$flatArray = [];
foreach($it as $v) {
$flatArray[] = $v; //Flatten array
}
//Note you can do array_unique on the flat array if you also need to flatten the array
$counts = array_count_values($flatArray); //Count
foreach ($array as &$subarray) {
foreach ($subarray as $index => $element) {
$counts[$element]--;
if ($counts[$element] > 0) { //If there's more than 1 left remove it
unset($subarray[$index]);
}
}
}
This will remove duplicates nested exactly on the 2nd level without flattening the original array.
http://sandbox.onlinephpfunctions.com/code/346fd868bc89f484dac48d12575d678f3cb53626
first you need to join your array before you can filter out the duplicates:
<?php
$allNames = [];
while($row = mysql_fetch_assoc($resultClient)){
$names = explode(",", $row['food']);
$allNames[] = $names;
}
$allNames = array_merge(...$allNames); //Join everything to a one dimensional array
$allNames = array_unique($allNames); // Only keep unique elementes
print_r($allNames);

create dynamic array within a array php

I have an sql query that returns the altitude of a place. I have exploded the result to separate longitude and latitude. The result is stored in array.
Now I want to create an array which should contain all the arrays returned by the explode function.
$sql_altitude = mysql_query("SELECT altitude FROM `navigatio_info`
WHERE bus_id='$bus_id'
AND driver_id ='$driver_id'
ORDER BY stop_no ASC
LIMIT 0 , 30");
while ($row = mysql_fetch_assoc($sql_altitude))
{
//echo $row['altitude'];
//$altitude=array();
$altitude=(explode("-",$row['altitude']));
print_r($altitude);
//$lat=array();
$lat=$altitude[0];
//print_r($lat);
echo '<br/>';
//$long=array();
$long=$altitude[1];
//print_r($long);
//echo '<br/>';
}
below is a static array defined:
<?php
$phpArray = array(array('Vadodara',22.3000,73.2000,5),
array('Valsad',20.6300,72.9300,2),
array('Thane',19.1724,72.9570,1));
)?>
I want $phpArray to have dynamic values generated from the query above
Please use mysqli_* functions since mysql_* functions are old now.
$phpArray = array();
while ($row = mysql_fetch_assoc($sql_altitude))
{
/*
I assume $row['altitude'] contains something like below string
$row['altitude'] = "place-latitude-longitute-altitude"
*/
$phpArray[] = explode("-",$row['altitude']);
}
print_r($phpArray);
$sql_altitude = mysql_query("SELECT altitude FROM `navigatio_info` WHERE bus_id='$bus_id'AND driver_id ='$driver_id' ORDER BY stop_no ASC LIMIT 0 , 30");
$phparray = array();
while ($row = mysql_fetch_assoc($sql_altitude))
{
$altitude=(explode("-",$row['altitude']));
$lat=$altitude[0];
$long=$altitude[1];
$phparray = array($lat,$lat);
}
echo "<pre>";
print_r($phparray)
echo "<pre>";
Please check above code:
as i understand your requirement use the following code.
$phpArray = array();
while ($row = mysql_fetch_assoc($sql_altitude)) {
$altitude=(explode("-",$row['altitude']));
$phpArray[]= $altitude;
}
print"<pre>";
print_r($phpArray);
print"</pre>";
above code will generate following array.
Array
(
[0] => Array
(
[0] => Vadodara
[1] => 22.3000
[2] => 73.2000
[3] => 5
)
[1] => Array
(
[0] => Valsad
[1] => 20.6300
[2] => 72.9300
[3] => 2
)
[2] => Array
(
[0] => Thane
[1] => 19.1724
[2] => 72.9570
[3] => 1
)
)
Hope this helps.

key value pair addition from query result, php

I am having some issues with the below, wanting to add the query result "id" as the key to the value "concat" -- Do I need a foreach for this? What is the best way?
$concatCol = mysqli_query( $connS, "SELECT id, ShipmentNumber, InvoiceNumber, BillofLading from testTable");
$data =array();
while ($row = mysqli_fetch_array($concatCol)) {
$id = $row["id"];
$ShipmentNumber = $row["ShipmentNumber"];
$InvoiceNumber = $row["InvoiceNumber"];
$BillofLading = $row["BillofLading"];
$concat = $ShipmentNumber.$InvoiceNumber.$BillofLading;
echo $concat."<br>";
$data[] = $concat;
}
I'm not really sure what your expected output is. But I think one of the following will work for you:
$data[]['id'] = $concat;
which will result in an array like this:
Array
(
[0] => Array
(
[id] => ShipmentNumberInvoiceNumberBillofLanding
)
[1] => Array
(
[id] => ShipmentNumberInvoiceNumberBillofLanding
)
)
The second option would be:
$data[$id] = $concat;
Which will yield a result like:
Array
(
[1] => ShipmentNumberInvoiceNumberBillofLanding
[4] => ShipmentNumberInvoiceNumberBillofLanding
)
Where the keys 1 and 4 are the $id for each returned row. In both example the ShipmentNumberInvoiceNumberBillofLanding would of course be the concatenated values for each row.

PHP: checking array to see if values match, display those values

I am generating an array from a while loop, and I would like to eventually use this array to display data.
while($row = $database->fetch(PDO::FETCH_ASSOC)
{
$value_1 = $row['value_1'];
$value_2 = $row['value_2'];
$data[] = array("value_1"=>$value_1,"value_2"=>$value_2);
}
so the $data[] would display using print_r I get something like this:
Array
(
[0] => Array
(
[value_1] => Hello World
[value_2] => venus
)
[1] => Array
(
[value_1] => Hello World
[value_2] => pluto
)
[2] => Array
(
[value_1] => Hello Moon
[value_2] => Halloween
)
)
My question is, how would I do a foreach loop or display such a way where if I wanted to get all data, but consolidate the same values?
Ex:
Hello World to venus pluto
Hello Moon to Halloween
I know those sentences doesn't make sense, but as you can see Hello World would be consolidated and I would need to add an " to" in between value_1 and value_2
Hope my question is understandable.
Thanks!
Try something like this. (Not Tested)
$match = array();
foreach($data as $d) {
if (isset($match[$d['value_1']])) {
$match[$d['value_1']] = $match[$d['value_1']].' '.$d['value_2'] ;
} else {
$match[$d['value_1']] = $d['value_1']. ' to '. $d['value_2'];
}
}
print_r($match);
I think for this first you need to create new array as follows:
$new_array = array();
//consider your original array is $data
foreach($data as $row){
if (array_key_exists($row['value_1'], $new_array)) {
$new_array[$row['value_1']] = $new_array[$row['value_1']]. " ".
$row['value_2'];
}
else {
$new_array[$row['value_1']] = $row['value_2'];
}
}
Then display it by iterating:
foreach($new_array as $key => $value){
echo $key ."to". $value;
}
foreach($data as $d) {
echo $d['value_1'], ' to ', $d['value_2']; // this is if you want to echo the content
// this code is to insert 'to' in the middle of value_1 and value_2
$value_2 = $d['value_2'];
unset($d['value_2']);
array_push($d, "to", $value_2);
unset($value_2);
}
Also you don't need to assign the $row value to another value:
$value_1 = $row['value_1']; // remove this
$value_2 = $row['value_2']; // remove this
$data[] = array("value_1" => $row['value_1'], "value_2" => $row['value_2']);

Categories