Merging arrays that are inside a foreach loop using PHP - php

I have following array:
Array
(
[0] => ALFA01
[1] => BETA02
[2] => GAMMA03
[3] => DELTA04
[4] => EPSILON05
[5] => ZETA06
[6] => THETA07
[7] => IOTA08
[8] => KAPPA09
[9] => LAMBDA10
)
Then I separate the values into characters and numbers in the following way:
foreach($portfolio as $value) {
$char = substr("$value", 0, 2);
$numb = substr("$value", 2);
and do a query using this values:
$query = "
SELECT id, typ1, typ2, typ3
FROM data_table
WHERE char = '$char'
AND numb = $numb
LIMIT 1";
$result = mysqli_query($mysqli, $query);
//Now we have some important variables that will help finding our result.
while($row = mysqli_fetch_array($result)) {
$id = $row['id'];
$typ1 = $row['typ1'];
$typ2 = $row['typ2'];
$typ3 = $row['typ3'];
}
Then I do some queries in case typ* are = 1 (it can be only 0 or 1).
if ($typ1 == 1) {
$query_id_num2 = "
SELECT id_num2
FROM values_table01
WHERE id_num1 = $id";
$result_id_num2 = mysqli_query($mysqli, $query_id_num2);
// Return an array with all ids.
$id_num2_typ01 = array();
while($row = mysqli_fetch_array($result_appln_id_num2)) {
$id_num2_typ01[] = ($row['id_num2']);
}
}
/== EDIT ==/
In each different typ we have a different values_table.
I'm now writing the complete query for typ2, so it will be emphasised.
// == /EDIT ==/
Then I do the same to typ2 and typ3...
if ($typ2 == 1) {
$query_id_num2 = "
SELECT id_num2
FROM values_table02
WHERE id_num1 = $id";
$result_id_num2 = mysqli_query($mysqli, $query_id_num2);
// Return an array with all ids.
$id_num2_typ02 = array();
while($row = mysqli_fetch_array($result_appln_id_num2)) {
$id_num2_typ02[] = ($row['id_num2']);
}
}
etc.
In the end I merge the three arrays (if they are set) and print the result on the screen:
// typ01
if (isset($id_num2_typ01)){
$id_num2_typ01 = $id_num2_typ01;
} else {
$id_num2_typ01 = array();
}
// typ02
if (isset($id_num2_typ02)){
$id_num2_typ02 = $id_num2_typ02;
} else {
$id_num2_typ02 = array();
}
// typ03
if (isset($id_num2_typ03)){
$id_num2_typ03 = $id_num2_typ03;
} else {
$id_num2_typ03 = array();
}
// merge arrays
$id_num2 = array_merge($id_num2_typ01,$id_num2_typ02,$id_num2_typ03);
// print it on screen
echo '<pre>id_num2:<br />';
print_r($appln_idNum2);
echo '</pre>';
} // this closes the above foreach, i.e. the code will loop to every value of the first array
As result I receive for example following data:
id_num2:
Array
(
[0] => 41558194
[1] => 44677841
[2] => 44503689
[3] => 40651770
[4] => 41667291
)
id_num2:
Array
(
[0] => 15458354
[1] => 35477154
[2] => 15703123
[3] => 95151111
[4] => 55567125
)
etc.
In our case we will have 10 small arrays like that.
My problem is: How can I merge this small arrays so in the ende I have only one array?
Thank you for your help to solve this particular problem. Maybe is there also another possibility to write the code to be better and more efficient.

Related

How to loop through statement results to insert into associative array in PHP

I cannot seem to get the syntax correct to loop through my results and insert them into an associative array- at the moment it is only giving me the first result and not looping through the rest. I've tried numerous combinations of foreach etc but just cannot complete this successfully.
Here is my code:
$count = array(
"timeinsert"=>"value",
"rfid"=>"value"
);
$readlags = "SELECT id_arduino, Device_id,time_inserted, message, message_type,
LAG(message) OVER(PARTITION BY device_id ORDER BY time_inserted)
AS 'Previous Entry'
FROM Arduino_Data
WHERE Datediff(Curdate(), time_inserted) < $period AND Device_id = $device AND message != 2
GROUP BY time_inserted ASC";
$result = $conn->query($readlags);
if (!$result) {
echo $conn->error;
}
while ($row = mysqli_fetch_array($result)) {
$eventtime = $row['time_inserted'];
$message = $row['message'];
$message_type = $row['message_type'];
$previous = $row['Previous Entry'];
if ($previous != 'Broken' and $previous != null) {
$catid = "SELECT RFID_id
FROM Cat_User
WHERE RFID_id = $previous ";
$result1 = $conn->query($catid);
if (!$result1) {
echo $conn->error;
}
while ($row1 = mysqli_fetch_array($result1)) {
$cat_id = $row1['RFID_id'];
//echo $cat_id . '<br>';
}
}
if ($message == "Broken" && $message_type == "BreakBeam" && $previous==$cat_id) {
$count["timeinsert"] = $eventtime;
$count["rfid"]=$previous;
}
}
print_r($count);
This is the output :
Array
(
[timeinsert] => 2020-09-17 16:02:44
[rfid] => 5609
)
When I do an array_push the results are the following :
Array
(
[0] => 2020-09-17 15:51:37
[1] => 23641
[2] => 2020-09-17 15:52:20
[3] => 5609
[4] => 2020-09-17 15:53:23
[5] => 5609
[6] => 2020-09-17 16:02:44
[7] => 5609
)
this because you overwritten all result in same variable so when you print reasult you will see last data written in variable.
1) define $count as array and $c to count array element like this
$count = array();
$c=0;
2) when you want to save new data but it in multidimensional array like this:
$count[$c]["timeinsert"] = $eventtime;
$count[$c]["rfid"]=$previous;
$c++;
3) retrieve your data like this:
$c=count($count);
for($i=0;$i<$c;$i++){
echo $count[$i]["timeinsert"];
echo $count[$i]["rfid"];
}

implode arrays in loop foreach but the result is double php

I want to get data from an array according to the code of the item above. but the array that I made actually produces a double result. the data array that I can only fit is the item
$query = "SELECT IDBRG,Disc FROM $RTL.tmasterbarang1 WHERE IDBRG IN (1167646,1170635,1170634)";
// echo $query;
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_array($result))
{
$a = $row['IDBRG'];
$b = $row['Disc'];
$arr1 = str_split($b);
foreach($arr1 as $x=>$x_value)
{
echo "<br>";
$queryz = "SELECT CAT_DISC_NBR FROM $RTL.cat_disc_test WHERE FLR_NBR = 1 AND CAT_DISC_CD = '".$x_value."' ";
// echo $queryz;
$resultz = mysqli_query($connect, $queryz);
$rowz = mysqli_fetch_array($resultz);
$elements[] = $rowz['CAT_DISC_NBR'];
}
echo $all = implode(',', $elements);
}
result of print_r($arr1)."<br>";
1. Array ( [0] => Y [1] => 4 [2] => S [3] => V )
2. Array ( [0] => Y [1] => 4 [2] => S [3] => V )
3. Array ( [0] => Y [1] => G [2] => 3 )
// and the each of array have value Y=69, 4=39, S=66, V=66, G=51, 3=38
echo $all = implode(',', $elements);
69,39,63,66
69,39,63,66,69,39,63,66
69,39,63,66,69,39,63,66,69,51,38
// i want it should be
69,39,63,66
69,39,63,66
69,51,38
When you add the data at
$elements[] = $rowz['CAT_DISC_NBR'];
this just keeps on adding data and the $elements array is never cleared out, so the next loop will just keep on adding data to the results of the last loop.
You need something like...
$a = $row['IDBRG'];
$b = $row['Disc'];
$arr1 = str_split($b);
$elements = []; // Reset list
This happens because you are adding data to elements every time and you never set it to empty again. You should empty the elements array before each foreach loop:
$elements=[];
foreach($arr1 as $x=>$x_value)
{
echo "<br>";
$queryz = "SELECT CAT_DISC_NBR FROM $RTL.cat_disc_test WHERE FLR_NBR = 1 AND CAT_DISC_CD = '".$x_value."' ";
// echo $queryz;
$resultz = mysqli_query($connect, $queryz);
$rowz = mysqli_fetch_array($resultz);
$elements[] = $rowz['CAT_DISC_NBR'];
}

How can I fix my php array?

so I have loop where it spits out each row of data from my database. Output show below
Array ( [0] => 1 [1] => 1 [2] => 1 [3] => Saratoga [4] => test [5] => 7-2 [6]
=> Red [7] => Bob [8] => Jill )
Array ( [0] => 2 [1] => 1 [2] => 2 [3] => Saratoga [4] => test 2 [5] => 3-3 [6]
=> White [7] => Bill [8] => Austin )
Array ( [0] => 3 [1] => 1 [2] => 3 [3] => Saratoga [4] => test 3 [5] => 2-2
[6] => Blue [7] => Austin [8] => jill )
how do I combine this into one array?
code is down below on how I am doing my loop for my array
$sql = "SELECT * FROM `2018-08-20`";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$rn = 1;
// output data of each row
$aa = 1;
while($row = $result->fetch_assoc()) {
$a = array($aa,$row["RaceNumber"], $row["HorseNum"], $row["Track"],
$row["HorseName"], $row["Odds"], $row["Color"], $row["JockeyName"],
$row["TrainerName"] );
for($x=0;$x < $a[1];$x++){
$aa++;
print_r($a);
echo "<br/>";
$rn++;
}
}
echo ' <button type="submit" name="submit"> Submit </button></form>';
echo "</table>";
} else {
echo "0 results";
}
Try this. In the following code we are storing all arrays in $all_data array.
$all_data = array();
while($row = $result->fetch_assoc()) {
$a = array($row["RaceNumber"], $row["HorseNum"], $row["Track"],
$row["HorseName"], $row["Odds"], $row["Color"], $row["JockeyName"],
$row["TrainerName"] );
$all_data[] = $a;
}
print_r($all_data);
If you just want an array containing the fields that you have coded in your loop, you should just code them into your query. I'm not sure what you are doing with the $aa in your array, but you have it there so I'm including it in my last example.
SQL APPROACH:
Note: The $aa will be missing.
$sql = "SELECT
`RaceNumber`,
`HorseNum`,
`Track`,
`HorseName`,
`Odds`,
`Color`,
`JockeyName`,
`TrainerName`
FROM `2018-08-20`";
$results = $conn->query($sql);
print_r($results);
YOUR CURRENT SETUP
$sql = "SELECT * FROM `2018-08-20`";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$rn = 1; //What are these for???
$aa = 1;
while($row = $result->fetch_assoc()) {
$a[] = array(
$aa,
$row["RaceNumber"],
$row["HorseNum"],
$row["Track"],
$row["HorseName"],
$row["Odds"],
$row["Color"],
$row["JockeyName"],
$row["TrainerName"]
);
}
print_r($a);
echo ' <button type="submit" name="submit"> Submit </button></form>';
echo "</table>";
} else {
echo "0 results";
}
You can try this also
$all_data = array();
while($row = $result->fetch_assoc()) {
$all_data[] = $row;
}
var_dump($all_data);
As the $row will be in array format , you can directly add that to array
you can read more on
http://php.net/manual/en/mysqli-result.fetch-assoc.php

PHP - Combine 2 arrays where key is the same multiple times

I have 2 arrays that i wish to combine, however the values in both arrays are the same but i still wish to combine them. Is this possible?
Lets say i have the following arrays:
Array ( [0] => 2683 [1] => 2683 [2] => 2683 [3] => 2683 [4] => 2683 [5] => 2683)
Array ( [0] => 2097152 [1] => 4194304 [2] => 6291456 [3] => 8391910 [4] => 234889216 [5] => 234889280)
I used array_combine but then it only displays 1 value. In this case i want they key to allow duplicates, or atleast bring them somehow together in an array where i can simply loop through them.
Is this possible with arrays? Or does anyone else have a better solution? I have to later loop through them and have the matched values, thats the point.
Below my code if that helps.
try {
$stmt = $pdo->prepare("SELECT deviceid, interfaceoid FROM poorten WHERE deviceid = '2683'");
$stmt->execute();
$deviceid = array();
$interfaceoid = array();
if($stmt->rowCount() > 0) {
while($row = $stmt->fetch()) {
//echo "" . $row['deviceid'] . " : ";
//echo "" . $row['interfaceoid'] . "</br>";
$deviceid[] = $row['deviceid'];
$interfaceoid[] = $row['interfaceoid'];
}
$result = array_combine($deviceid, $interfaceoid);
var_dump($result);
}
}
catch(PDOException $e) {
echo "Something went wrong: " . $e->getMessage() . "";
}
Use deviceid as an array key:
$result = [];
if ($stmt->rowCount() > 0) {
while ($row = $stmt->fetch()) {
if (!isset($result[$row['deviceid']])) {
$result[$row['deviceid']] = [];
}
$result[$row['deviceid']][] = $row['interfaceoid'];
}
}
var_dump($result);
Try this, for live demo and live demo
foreach($values as $k => $v)
{
$result[$keys[$k]][] = $v;
}
$result = array_map(function($v){return count($v) > 1 ? $v : $v[0];}, $result);

Php Loop with a List

I have a PHP code like that:
$cityCount=10;
$currentUsers = array();
$addedUsers = array();
for ($cityId = 1; $cityId <= $cityCount; $cityId++) {
$currentUsers[$cityId] = array();
$addedUsers[$cityId] = array();
}
However, I want to change the for and I want to define an array for cities because new city will be added and it'i city id will be 22(not 11. If it could be 11 there was going to be just one change at code $cityCount=11; but city id is not sequential now.)
As like:
[1,2,3,4,5,6,7,8,9,10,22]
I want to iterate over that array.
Also I have a code like that:
for ($cityId = 1; $cityId <= $cityCount; $cityId++) {
foreach ($addedUsers[$cityId] as $userId) {
if($added) $addSql .= ",\n";
$addSql .= '(' . $userId . ", " . $cityId . ')';
$added++;
}
How to change this code according to new version of code?
$citiesids = array(1,2,3,4,5,6,7,8,9,10,22);
$currentUsers = array();
$addedUsers = array();
foreach ($citesids as $cityId) {
$currentUsers[$cityId] = array();
$addedUsers[$cityId] = array();
}
is that what you need?
Use foreach:
$cities = array(1,2,3,4,5,6,7,8,9,10,22);
foreach ($cities as $cityId) {
// use $cityId as before.
}
I'm not really sure what you mean exactly, but perhaps you mean using the array of cityIds instead of a simple counter?
In that case, simply use a foreach:
foreach ($cities as $cityId)
I assume you want to iterate over cities, but not all of them
$cityCount=22;
$cities = array(1,2,3,4,5,6,7,8,9,10,22);
for ($cityId = 1; $cityId <= $cityCount; $cityId++) {
// only handle the cases that where cityid is in the cities-array
if (!in_array($cityId, $cities)) continue;
// do what you like here
}
$cityCount=10;
$currentUsers = array();
$addedUsers = array();
for ($cityId = 1; $cityId <= $cityCount; $cityId++) {
$currentUsers[$cityId] = array();
array_push($addedUsers,$cityId);
}
echo '<pre>';
print_r($addedUsers);
echo '</pre>';
array_push($addedUsers,22);//whatever city you want to added (22 for example)
echo '<pre>';
print_r($addedUsers);
echo '</pre>';
OUTPUT
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
[7] => 8
[8] => 9
[9] => 10
)
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
[7] => 8
[8] => 9
[9] => 10
[10] => 22 // just Added
)
As I suspected, it should be SQL query, not PHP code
Something like
select * from user WHERE where city IN (SELECT * FROM cities)
or whatever suits your hidden and secret needs

Categories