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