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

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);

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'];
}

Merging arrays that are inside a foreach loop using 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.

combine arrays and concat value?

Little complex to explain , so here is simple concrete exemple :
array 1 :
Array
(
[4] => bim
[5] => pow
[6] => foo
)
array 2 :
Array
(
[n] => Array
(
[0] => 1
)
[m] => Array
(
[0] => 1
[1] => 2
)
[l] => Array
(
[0] => 1
[1] => 4
[2] => 64
)
And i need to output an array 3 ,
array expected :
Array
(
[bim] => n-1
[pow] => Array
(
[0] => m-1
[1] => m-2
)
[foo] => Array
(
[0] => l-1
[1] => l-4
[2] => l-64
)
Final echoing OUTPUT expected:
bim n-1 , pow m-1 m-2 ,foo l-1 l-4 l-64 ,
I tried this but seems pity:
foreach($array2 as $k1 =>$v1){
foreach($array2[$k1] as $k => $v){
$k[] = $k1.'_'.$v);
}
foreach($array1 as $res =>$val){
$val = $array2;
}
Thanks for helps,
Jess
CHALLENGE ACCEPTED
<?php
$a = array(
4 => 'bim',
5 => 'pow',
6 => 'foo',
);
$b = array(
'n' => array(1),
'm' => array(1, 2),
'l' => array(1, 4, 64),
);
$len = count($a);
$result = array();
$aVals = array_values($a);
$bKeys = array_keys($b);
$bVals = array_values($b);
for ($i = 0; $i < $len; $i++) {
$combined = array();
$key = $aVals[$i];
$prefix = $bKeys[$i];
$items = $bVals[$i];
foreach ($items as $item) {
$combined[] = sprintf('%s-%d', $prefix, $item);
};
if (count($combined) === 1) {
$combined = $combined[0];
}
$result[$key] = $combined;
}
var_dump($result);
?>
Your code may be very easy. For example, assuming arrays:
$one = Array
(
4 => 'bim',
5 => 'pow',
6 => 'foo'
);
$two = Array
(
'n' => Array
(
0 => 1
),
'm' => Array
(
0 => 1,
1 => 2
),
'l' => Array
(
0 => 1,
1 => 4,
2 => 64
)
);
You may get your result with:
$result = [];
while((list($oneKey, $oneValue) = each($one)) &&
(list($twoKey, $twoValue) = each($two)))
{
$result[$oneValue] = array_map(function($item) use ($twoKey)
{
return $twoKey.'-'.$item;
}, $twoValue);
};
-check this demo Note, that code above will not make single-element array as single element. If that is needed, just add:
$result = array_map(function($item)
{
return count($item)>1?$item:array_shift($item);
}, $result);
Version of this solution for PHP4>=4.3, PHP5>=5.0 you can find here
Update: if you need only string, then use this (cross-version):
$result = array();
while((list($oneKey, $oneValue) = each($one)) &&
(list($twoKey, $twoValue) = each($two)))
{
$temp = array();
foreach($twoValue as $item)
{
$temp[] = $twoKey.'-'.$item;
}
$result[] = $oneValue.' '.join(' ', $temp);
};
$result = join(' ', $result);
As a solution to your problem please try executing following code snippet
<?php
$a=array(4=>'bim',5=>'pow',6=>'foo');
$b=array('n'=>array(1),'m'=>array(1,2),'l'=>array(1,4,64));
$keys=array_values($a);
$values=array();
foreach($b as $key=>$value)
{
if(is_array($value) && !empty($value))
{
foreach($value as $k=>$val)
{
if($key=='n')
{
$values[$key]=$key.'-'.$val;
}
else
{
$values[$key][]=$key.'-'.$val;
}
}
}
}
$result=array_combine($keys,$values);
echo '<pre>';
print_r($result);
?>
The logic behind should be clear by reading the code comments.
Here's a demo # PHPFiddle.
//omitted array declarations
$output = array();
//variables to shorten things in the loop
$val1 = array_values($array1);
$keys2 = array_keys($array2);
$vals2 = array_values($array2);
//iterating over each element of the first array
for($i = 0; $i < count($array1); $i++) {
//if the second array has multiple values at the same index
//as the first array things will be handled differently
if(count($vals2[$i]) > 1) {
$tempArr = array();
//iterating over each element of the second array
//at the specified index
foreach($vals2[$i] as $val) {
//we push each element into the temporary array
//(in the form of "keyOfArray2-value"
array_push($tempArr, $keys2[$i] . "-" . $val);
}
//finally assign it to our output array
$output[$val1[$i]] = $tempArr;
} else {
//when there is only one sub-element in array2
//we can assign the output directly, as you don't want an array in this case
$output[$val1[$i]] = $keys2[$i] . "-" . $vals2[$i][0];
}
}
var_dump($output);
Output:
Array (
["bim"]=> "n-1"
["pow"]=> Array (
[0]=> "m-1"
[1]=> "m-2"
)
["foo"]=> Array (
[0]=> "l-1"
[1]=> "l-4"
[2]=> "l-64"
)
)
Concerning your final output you may do something like
$final = "";
//$output can be obtained by any method of the other answers,
//not just with the method i posted above
foreach($output as $key=>$value) {
$final .= $key . " ";
if(count($value) > 1) {
$final .= implode($value, " ") .", ";
} else {
$final .= $value . ", ";
}
}
$final = rtrim($final, ", ");
This will echo bim n-1, pow m-1 m-2, foo l-1 l-4 l-64.

How do you append a number for duplicate records in a mysql table?

I think the solution is somewhat easy, of course it is eluding me.
I have two tables and am Joining them on a field with identical values:
example records:
art0001,
art0001,
art0001,
art0002,
art0002,
art0003
What I want to do is to append a number to count every duplicate and echo it out like this:
art0001-1,
art0001-2,
art0001-3
art0002-1,
art0002-2,
art0003-1
I came up with this code, but the output just adds a number, but does not restart when a new duplicate is found.
$query = mysql_query( "SELECT * FROM product_image JOIN my_art ON product_folder = product_code" );
if( !$query ) {
die( mysql_error() );
}
$row = mysql_fetch_array($query);
$i = 0;
while($row = mysql_fetch_array($query)) {
if($row['COUNT(base_folder)'] < 1 && $row['image_type'] == 'B' && $row['view'] == 'FF') {
echo $row['base_folder']."-".$i++;
echo "<br />";
}
}
Can anyone please help me and tell me what I did wrong?
If you want to keep a counter for each 'product' individually, you'll have to check that the product is still the same in the loop, or if this another product. Mind you: the order by clause in the query is needed for this to work.
<?php
$query = mysql_query( "SELECT * FROM product_image JOIN my_art ON product_folder = product_code ORDER BY product_folder" );
if( !$query ) {
die( mysql_error() );
}
$row = mysql_fetch_array($query);
$i = 0;
$last = '';
while($row = mysql_fetch_array($query)) {
if( $row['COUNT(base_folder)'] < 1 && $row['image_type'] == 'B' && $row['view'] == 'FF' ) {
if( $last !== $row['basefolder'] ) {
$i = 0;
}
echo $row['base_folder']."-".$i++;
echo "<br />";
$last = $row['basefolder'];
}
}
You can use an array to keep track of the item count:
<?php
$test_data = array(
'art0001',
'art0001',
'art0001',
'art0002',
'art0002',
'art0003',
);
$item_count = array();
foreach($test_data as $item){
if( isset($item_count[$item]) ){
$item_count[$item]++;
}else{
$item_count[$item] = 1;
}
echo $item . '-' . $item_count[$item] . PHP_EOL;
}
Here is a simple function for taking an array with duplicate values and appending a number to only the duplicate names.
Array
(
[0] => samename
[1] => namesame
[2] => samename
[3] => namename
[4] => namename
[5] => notsame
[6] => samename
)
Array
(
[0] => samename
[1] => namesame
[2] => samename(2)
[3] => namename
[4] => namename(2)
[5] => notsame
[6] => samename(3)
)
function uniqueNames($array){
$alreadyoccured=array();
$newarray=array();
foreach($array as $arr){
if(array_key_exists($arr,$alreadyoccured)){
$alreadyoccured[$arr]=$alreadyoccured[$arr]+1;
$newarray[]=$arr.'('.$alreadyoccured[$arr].')';
}else{
$alreadyoccured[$arr]=1;
$newarray[]=$arr;
}
}
return $newarray;
}

Categories