Collect duplicate data in array using php - php

this is my sample array data from bio-metrics
I just want to collect data that has the same bio_id and date
temp:[
0:{
bio_id:"1"
date:"2017-10-05"
date_time:"2017-10-05 08:00:22"
device_name:"biometrics"
time:"08:00:22"
}
1:{
bio_id:"1"
date:"2017-10-05"
date_time:"2017-10-05 08:00:23"
device_name:"biometrics"
time:"08:00:23"
}
2:{
bio_id:"2"
date:"2017-10-05"
date_time:"2017-10-05 08:06:29"
device_name:"biometrics"
time:"08:06:29"
}
3:{
bio_id:"1"
date:"2017-10-05"
date_time:"2017-10-05 15:06:47"
device_name:"biometrics"
time:"15:06:47"
}
4:{
bio_id:"2"
date:"2017-10-05"
date_time:"2017-10-05 16:01:50"
device_name:"biometrics"
time:"16:01:50"
}
]
I been stuck with this code that I made, and don't know how I should manipulate it, or how I will store it properly, I have try some array function but it gives different result to my data
$len = count($temp);
for ($i=0; $i <$len ; $i++) {
$id = $temp[$i]['bio_id'];
$date = $temp[$i]['date'];
for ($x=0; $x < $len; $x++) {
if ($id == $temp[$x]['bio_id'] && $date == $temp[$x]['date']) {
$data[] = $temp[$x];
$int[] = $x;
}
}
}
I don't know how I should manipulate it, or how I will store it properly, I have try some array function but it gives different result to my data

This code will work to collect duplicate in the array on the basis of id and date
$newTemp = array();
foreach($temp as $value){
$newTemp[$value['id'].'_'.$value['date']][] = $value;
}

$newTemp = array();
for($temp as $value){
$key = $value->id." ".$value->date;
if(isset($newTemp[$key])){
$newTemp[$key] = array_merge($newTemp[$key],$value);
}else{
$newTemp[$key] = $value;
}
}

I just want to collect data that has the same bio_id and date
The easiest way is to iterate over the input array and aggregate the data into a new array, indexed by key generated using the bio_id and date fields. This way, a duplicate entry can be easily identified because the key already exists in the output array.
$input = array(/* the big input array here */);
// Build the output here
$output = array();
foreach ($input as $item) {
$key = $item['bio_id'].':'.$item['date'];
if (array_key_exists($key, $output)) {
// This is a duplicate
// Ignore the data, update only the count
$output[$key]['count'] ++;
} else {
// This is the first time this combination is processed
// Copy the input
$output[$key] = $item;
// Keep in 'count' how many times this combination exists in the input
$output[$key]['count'] = 1;
}
}
Each entry of $output is the first entry of $input that has the same combination of bio_id and date. Additional, the value of count is the number of entries of $input that share that pair of bio_id and date.
Work on this example if you need to aggregate the data in a different way (keep all duplicates, instead of their number, f.e.).
Another example that keeps the duplicates:
// Build the output here
$output = array();
foreach ($input as $item) {
$key = $item['bio_id'].':'.$item['date'];
if (array_key_exists($key, $output)) {
// This is a duplicate; add it to the list
$output[$key]['all'][] = $item;
} else {
// This is the first time this combination is processed
// Copy important values (bio_id and date) from the input
$output[$key] = array(
'bio_id' => $item['bio_id'],
'date' => $item['date'],
// Store the entire $item into a list
'all' => array($item),
);
}
}
Read about PHP arrays how to access their elements using the square brackets syntax and how to create or modify their values.

Related

How to merge values from similar rows in an array to rows containing both data in php

I have a phone book array I get from a database, where everyone appears once with their stationary phone number and a second with their mobile number.
I need to make this an array where everyone has only one line, with their phone number and mobile number
//My array
$data = array(
array('name'=>'robert','family'=>'bridgstone','home'=>'0258101234'),
array('name'=>'robert','family'=>'bridgstone','phone'=>'07258101235'),
array('name'=>'dan','family'=>'swartz','home'=>'098101244'),
array('name'=>'ben','family'=>'wais','home'=>'0447256155778'),
array('name'=>'ben','family'=>'wais','phone'=>'04472861558878'),
);
//The result that should come out
$data = array(
array('name'=>'robert','family'=>'bridgstone','home'=>'0258101234','phone'=>'07258101235'),
array('name'=>'dan','family'=>'swartz','home'=>'098101244','phone'=>''),
array('name'=>'ben','family'=>'wais','home'=>'0447256155778','phone'=>'04472861558878')
);
I would do it the following way:
first I would generate a unique key that identify the row (in your case the name and the family, for example).
then check if a element with the same key exist, if it already exist merge the two component.
Optional if you only want an array of values transform the result with array_value function.
$dataArray = array(
array('name'=>'robert','family'=>'bridgstone','home'=>'0258101234'),
array('name'=>'robert','family'=>'bridgstone','phone'=>'07258101235'),
array('name'=>'dan','family'=>'swartz','home'=>'098101244'),
array('name'=>'ben','family'=>'wais','home'=>'0447256155778'),
array('name'=>'ben','family'=>'wais','phone'=>'04472861558878'),
);
$result = [];
foreach($dataArray as $data){
//Just in case that the name or the family is not assigned (operator ??)
$key = ($data['name']??'').'-'.($data['family']??'');
$result[$key] = array_merge($result[$key]??[],$data);
}
//Optional, get only the array values
$result = array_values($result);
I did so
$data = array(
array('name'=>'robert','family'=>'bridgstone','home'=>'0258101234'),
array('name'=>'robert','family'=>'bridgstone','phone'=>'07258101235'),
array('name'=>'dan','family'=>'swartz','home'=>'098101244'),
array('name'=>'ben','family'=>'wais','home'=>'0447256155778'),
array('name'=>'ben','family'=>'wais','phone'=>'04472861558878'),
);
count($data) < 2 ? exit(): $data;
for($i=0;$i<count($data);$i++){
$array_unique[$i] = $data[$i]["name"];
$array_unique[$i] = $data[$i]["family"];
}
$array_unique = array_unique($array_unique);
if(count($array_unique) == 1){
$last_array[0]=$array_unique[0];
$last_array[0]["phone"]=$array_unique[0]["phone"];
}
else{
$array_uniqueKeys = array_keys($array_unique);
for($i = 0;$i < count($array_unique);$i++){
$firstIndex = $i + 1;
$firstIndex == count($array_unique) ? $nextKey = count($data) : $nextKey = $array_uniqueKeys[$firstIndex];
$paar = $nextKey - $array_uniqueKeys[$i];
$dataslice = array();
$i3=0;
for($i2 = $array_uniqueKeys[$i];$i2 < ($array_uniqueKeys[$i]+$paar);$i2++){
if(in_array($i2,$array_uniqueKeys)){
$last_array[$i]=$data[$i2];
}
else{
$last_array[$i]["phone"]=$data[$i2]["phone"];
}
$i3++;
}
}
}
print_r($last_array);

“How can to fix the problem ‘ number_format error

I would like to shorten the result. I have used nummber_format but always an error appears.Can someone help me.
$arr = array();
foreach ($order->orderPositions as $tax) {
$arr[] = $tax->tax;
}
$unique_data = array_unique($arr);
foreach ($unique_data as $val) {
$totalTaxes[$val] = $order->orderPositions->where('tax',
$val)->sum('TotalPriceWithTax');
}
/*help is needed here*/ number_format((float)$unique_data,2);
Loop the array and save them as the new format either in a new array or the same
$unique_data = array_unique($arr);
foreach ($unique_data as &$val) { //notice the & if you want to change the data points in the unique array
$totalTaxes[$val] = $order->orderPositions->where('tax', $val)->sum('TotalPriceWithTax');
$val = number_format($val,2); // replaces the data in unique array
$new[] = number_format($val,2); // add to new array if you need unique array
}

How to pull csv import into an associative array and name the keys automatically?

I have a csv file where the first line shows the name of each row. This name should be the key for an associative array. Currently I am pulling this in manually and if the row order changes it will break the functionality.
How can I retrieve the names from line 1 and create keys out of it?
$csv = array();
$index = 0;
while ($row = fgetcsv($fp)) {
if ($row[0] == NULL)
continue;
else{
$index++;
foreach($row as $csvdata){
list(
$csv[$index]['column 1 name'],
$csv[$index]['column 2 name']
)
= explode(';',$csvdata);
}
}
}
Try converting the very first line of the file, which contains the names/keys, into an array. Then use those keys to populate the associate array as you parse the remaining lines.
$keys = array();
$csv = array();
$index = 0;
while ($row = fgetcsv($fp)) {
if ($index == 0) {
$keys = explode(',', $row);
}
else {
$csv[$keys[index-1]] = $row;
}
++$index;
}
This answer assumes that what you want here is an associate array where the keys correspond to the names in the first row, and the values correspond to each row in the CSV import.

How to save value in foreach cycle?

I have foreach cycle in PHP. It is going trough json items, and for every item I have value that changes. I set my cycle to run every 20min.
I need my value to be saved and next time foreach runs for that item I need to assign at the beginning old value to variable so I can compare old and new value in foreach cycle.
here is the code:
// Parse results and extract data to display
foreach($json as $quote)
{
//add before value
$state1 = $state2;
// assign object elements to vars
$q_change = $quote->c;
$q_price = $quote->l;
$q_name = $quote->t;
$q_changep = $quote->cp;
$q_symbol = $quote->t;
$q_ltrade = $quote->lt;
$q_exch = $quote->e;
$state2 = $q_change;
$parametar = $q_change - $state1;
// Define class based on change
if ( $parametar < -0.3 ) { $chclass = "minus"; }
else if ( $parametar > 0.3 ) { $chclass = "plus"; }
else if ( $q_change < 0 ) { $chclass = "minus"; }
else if ( $q_change > 0 ) { $chclass = "plus"; }
else { $chclass = "zero"; $q_change = "0.00"; }
}
Any idea how that might work?
You will have to save the JSON on the file system to retrieve the values on subsequent runs:
$oldJsonFile = '/path/to/data.json';
if (is_file($file)) {
$oldJson = file_get_contents($oldJsonFile);
}
// Do the work, and then store it back to the file system
file_put_contents($cacheFile, $newJson);
I'd imagine you are looking to do something like the following. Sessions will store your data for the next foreach execution.
session_start();
$previousData = $_SESSION['PreviousData'];
foreach($array as $key => $value){
//... all your foreach calculations
//end of foreach
}
$_SESSION['PreviousData'] = $thisData;
Alternatively you could store the data into a database, that's what they are for. Then you'll be free to do all kinds of interesting queries on past records etc.

Php pushing values to a 2-dimensional array

i've a 2-dimensional array and i want to push values to it with a while loop like;
$arr[0][1] = 1. value
$arr[0][2] = 2. value
i ve tried
while($zRow = mysql_fetch_array($zQuery))
{
$props[]['name'] =$zRow['name'];
$props[]['photo'] =$zRow['thumbnail'];
}
this loop pushes name to $props[0][name] and thumbnail to $props[1][photo]
i also tried
$j = 0;
while($zRow = mysql_fetch_array($zQuery))
{
$props[$j]['name'] =$zRow['name'];
$props[$j]['photo'] =$zRow['thumbnail'];
$j+=1;
}
that works but with this i when i use foreach loop later, it makes trouble like "Illegal offset type"
and here is my foreach loop
foreach($props as $no)
{
echo $props[$no]['name'];
}
now my questions;
1) are there any other way than while loop with $j variable like array_push for 2-dimensional arrays
2)how can i use foreach loop for 2-dimensional arrays
You could change the first loop to the following:
while($zRow = mysql_fetch_array($zQuery))
{
$row = array();
$row['name'] = $zRow['name'];
$row['photo'] = $zRow['thumbnail'];
$props[] = $row;
}
Your method also works, but you need that extra variable.
In your second loop, what you actually need to be doing is:
foreach($props as $index => $array)
{
echo $props[$index]['name'];
// OR
echo $array['name'];
}
Pushing anything onto an array with $myArray[] = 'foo' will increment the array's counter.
For multidimensional array, you need to populate the "inner" array, then push it to the "outer" (in your case $props) array.
while($zRow = mysql_fetch_array($zQuery)) {
$data = array('name' => $zRow['name'], 'photo' => $zRow['thumbnail']);
$props[] = $data;
}
To iterate over multidimensional arrays whose depth is known:
foreach ($props as $prop) {
foreach ($prop as $key => $value) {
echo "{$key} => {$value}" . PHP_EOL;
}
}
If the depth of the nesting is not known, you may have to use a recursive function to gather the data.

Categories