Difference between two arrays containing numbers as string - php

I´ve got a question about compairing two (text)arrays. I obtained two arrays from a loop containing numbers as shown below:
array(96) { [1]=> string(2) "20" [2]=> string(2) "18" [3]=> string(2)...
array(96) { [1]=> string(3) "135" [2]=> string(3) "103" [3]=> string(2) "88"
What I want is a new array which contains the difference of the values (1-2). This means that the 2 arrays above will results in the following new (text)array
array(96) { [1]=> string(3) "-115" [2]=> string(3) "-85" [3]=> string(2)
Can someone help me?

You could do this with one foreach-loop. And then substract them from each other. You just need the same count of elements in $array and in $array2.
$new = array();
foreach($array as $key => $val) {
$new[] = (string) ($val - $array2[$key]);
}
If it doesn't matter if the values are integers, you can remove the type casting (string).

this is a function,
function foo($array1, $array2){
$resultArray = array();
for($i=0; i<count($array1); $i++){
$resultArray[] = (string)((int)$array1[$i] - (int)$array2[$i]);
}
return $resultArray;
}

Hope this will help :)
<?php
$a=array(20,18);
$b=array(135,103);
function fr($d,$d1){
global $c;
$c[]=$d-$d1;
}
array_map('fr',$a,$b);
var_dump($c);

Related

how to compare multiple arrays for higher value based on one specific key?

I have multiple arrays. I want to compare these arrays key values with one another and output only one array which has the higher value than others. Here is my array
array(4) { ["type"]=> string(6) "Person" ["relevance"]=> string(8) "0.645481" ["count"]=> string(1) "1" ["text"]=> string(15) "RAJESH NELATURI" }
array(4) { ["type"]=> string(6) "Person" ["relevance"]=> string(8) "0.567918" ["count"]=> string(1) "2" ["text"]=> string(11) "Layoutlands" }
array(4) { ["type"]=> string(6) "Person" ["relevance"]=> string(8) "0.546824" ["count"]=> string(1) "1" ["text"]=> string(9) "N. Rajesh" }
I want to compare the key "relevance" and filter the array which has higher relevance value. In this case The first array which has the value "0.645481" and print the arrays key[text]. Here it should print RAJESH NELATURI
Here is a solution :
$higher = array('relevance' => 0);
foreach($myArray as $key) {
if($key['relevance'] > $higher['relevance']){
$higher = $key;
}
}
At the end, $higher will have the biggest relevance and is equal to :
$higher = array(4) { ["type"]=> string(6) "Person" ["relevance"]=> string(8) "0.645481" ["count"]=> string(1) "1" ["text"]=> string(15) "RAJESH NELATURI" }
now you can print the higher text :
echo $higher['text'];
UPDATE:
But it seems all 'relevance' values in your array are string, So they can not be compared with each other! you have to change them to float,
Try to produce this array in another way to have float values,
If you can't, Try this code instead :
$higher = array('relevance' => 0);
foreach($myArray as $key) {
if((float)$key['relevance'] > (float)$higher['relevance']){
$higher = $key;
}
}
this code changes string to float before compare.
find the relevance with max value, and the index. Here is the code, hope it helps.
$relevances = array_column($array, 'relevance');
$values = array_values($relevances);
$map = array_combine($values, array_keys($$relevances));
echo $array[$map[max($values)]]['text'];
Iterate through the arrays in a replace-if-higher basis.
$currentMax = PHP_INT_MIN; // it is impossible for any entries to be smaller than this value
foreach($arrays as $array){
$keyValue = $array["relevance"]; // not exactly sure what you mean by "key value"
if($keyValue > $currentMax){
$currentMax = $keyValue;
$currentName = $array["text"]'
}
}
$currentName should be set as lonig as $arrays is not empty and the $keyValue of any entries is greater than PHP_INT_MIN.

How to mixing an array values in order?

I'm trying to mix arrays values to display in order:
$array_one = array('a','b','c');
$array_two = array('1','2','3','4','5');
The result should be:
array('a','1','b','2','c','3','4','5');
Thank you.
This gives you what you want
$array_one = array('a','b','c');
$array_two = array('1','2','3','4','5');
$maxCount = max(array(count($array_one),count($array_two)));
$result = array();
for ($i=0; $i < $maxCount; $i++) {
if (!empty($array_one[$i])) {
$result[] = $array_one[$i];
}
if (!empty($array_two[$i])) {
$result[] = $array_two[$i];
}
}
var_dump($result);
Output
array(8) {
[0]=>
string(1) "a"
[1]=>
string(1) "1"
[2]=>
string(1) "b"
[3]=>
string(1) "2"
[4]=>
string(1) "c"
[5]=>
string(1) "3"
[6]=>
string(1) "4"
[7]=>
string(1) "5"
}
If both arrays have the same number of elements you could use array_walk and array_combine to create what you want.
$array_one = array('a','b','c','d','e');
$array_two = array('1','2','3','4','5');
$combined_array = array_combine($array_one, $array_two);
array_walk($combined_array, create_function('$value, $key', 'echo "$key $value ";'));
Hi #andrei you first find the length of both arrays, create a new array for the result,use two for loops in the inner loop just assign the values in new array and increment the loops. hope it give you expected result.

PHP - Compare 2 multidimensional arrays and output values if equal fields in array

I have 2 Arrays in 2 variables and both of them containing exactly the same values in the fields (in the 1st array = "image_id"-field and in the 2nd array = "ID-field").
I need to compare the 2 fields and would like to output the imagepath string of the 1st array (if the "ID"-field of 1st array and the field of 2nd array are equal)
Something like this:
if "2146" from 1st multi-array is equal to "2146" from 2nd multi-array, then echo apple.jpg..
But how does that work? Its really freakin me out the last days.. thanks in advance for your replies.
$multidimensional_array1:
array(4) {
[0]=>
string(9) "apple.jpg"
["imagepath"]=>
string(9) "apple.jpg"
[1]=>
string(4) "2146"
["image_id"]=>
string(4) "2146"
}
array(4) {
[0]=>
string(10) "ananas.jpg"
["imagepath"]=>
string(10) "ananas.jpg"
[1]=>
string(4) "2037"
["image_id"]=>
string(4) "2037"
}
array(4) {
[0]=>
string(8) "nuts.jpg"
["imagepath"]=>
string(8) "nuts.jpg"
[1]=>
string(4) "2024"
["image_id"]=>
string(4) "2024"
}
$multidimensional_array2:
array(2) {
[0]=>
string(4) "2146"
["ID"]=>
string(4) "2146"
}
array(2) {
[0]=>
string(4) "2037"
["ID"]=>
string(4) "2037"
}
array(2) {
[0]=>
string(4) "2024"
["ID"]=>
string(4) "2024"
}
As long as the arrays have the same keys, length and order, you can iterate over one and and pick values from both.
$len = count($arr1);
for ($i = 0; $i < $len; $i++)
{
if ($arr1[$i]['image_id'] == $arr2[$i]['ID'])
{
// output $arr1[$i]['imagepath']
}
}
If the information is from two tables in the same database, you would be better off by just joining the tables together. If the arrays are not ordered the same or not of the same length (so that $i might reference different elements in both arrays), use one as a lookup table:
$lookup = array();
foreach ($arr2 as $element)
{
$lookup[$element['ID']] = $element;
}
foreach ($arr1 as $element)
{
if (isset($lookup[$element['image_id']]))
{
// output $element['imagepath']
}
}
foreach($multidimensional_array1 as $arr1){
foreach($multidimensional_array2 as $arr2){
if($arr2['id']==$arr1['image_id']){
echo $arr1['imagepath'];
}
}
}
Note: The larger the arrays become the longer this will take.

PHP Array, Move Elements [duplicate]

This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 1 year ago.
I am creating an array from several text boxes. I am needing to move the elements in the array to insert into the database. Here is the array:
array(2) { [0]=> string(7) "nameone" [1]=> string(7) "nametwo" }
array(2) { [0]=> string(6) "ageone" [1]=> string(6) "agetwo" }
array(2) { [0]=> string(13) "parentnameone" [1]=> string(13) "parentnametwo" }
array(2) { [0]=> string(14) "parentemailone" [1]=> string(14) "parentemailtwo" }
array(2) { [0]=> string(14) "parentphoneone" [1]=> string(14) "parentphonetwo" }
I want to end up with an insert statement such as:
nameone, ageone, parentnameone, parentemailone, parentphoneone
and next row to insert would be
nametwo, agetwo, parentnametwo, parentemailtwo, parentphonetwo
I have tried to create an array with multiple for each loops but I end up with an array that i need to move the keys which brings be back to my original problem.
Is there a method to this madnaess?
Well, lets say your main array contains 5 arrays with 2 elements each. Lets call that $mainArr. "2" in the first line is no. of elements in each subarray. or if the subarraays are not of equal lengths, then the its the length of the largest subarray.
for($i=0;$i<2;$i++) {
foreach($mainArr as $key => $a) {
$ins[$i][] = $a[$i];
} // form an array with insert elements
}
// traverse that to form inserts
foreach($ins as $key => $arr) {
$statements[] = implode(",", $ins[$key]);
}
echo '<pre>';
print_r($statements);
I think thats what you want. If not, let me know. Hope that helps!
$l = count($array[0]);
for ($i=0; $i<$l; $i++) {
// access values like this:
$name = $array[0][$i]; // equals nameone first time and nametwo second time
$age = $array[1][$i];
$parentname = $array[2][$i];
$parentemail = $array[3][$i];
$parentphone = $array[3][$i];
// insert into DB here
}
#!/usr/bin/php
<?php
$val = array('name', 'age', 'parentname', 'parentemail');
$key = array('one', 'two', 'three', 'four', 'five');
$valone = array();
foreach ($val as $k)
array_push($valone, $k.$key[0]);
var_dump($valone);
?>
Outputs :
array(4) {
[0]=>
string(7) "nameone"
[1]=>
string(6) "ageone"
[2]=>
string(13) "parentnameone"
[3]=>
string(14) "parentemailone"
}
Is this what you want you to do ?

Need help with PHP array

Can anybody help me out, I'm stuck, don't know how to write a php nested for loop to convert into a key value array.
This is the array structure.
Needed to turn into key value array( combining JobDescription and userdetail array together)
array(2) {
["jobDescription"]=> array(5) {
["funeralFor"]=> string(6) "Myself"
["serviceType"]=> string(1) "1"
["religionType"]=> string(1) "2"
["area"]=> string(4) "2154"
["customerComment"]=> string(6) "fdfddf"
}
["userDetail"]=> array(6) {
["contactEmail"]=> string(16) "fdddf#fffgfg.com"
["contactFirstName"]=> string(6) "fddfdf"
["contactLastName"]=> string(6) "fddffd"
["contactPhoneNumber"]=> string(10) "0420988191"
["signup"]=> array(2) {
["id"]=> string(32) "8048f0f7106c336e1a8825d1d3bec902"
["input"]=> string(3) "k5m"
}
["agreement"]=> string(1) "1"
}
}
Thanks so much in advance
You have two arrays stored in an array. You want the values of both arrays under one array instead of two subarrays?
$newArray = array_merge($array['jobDescription'], $array['userDetail']);
I think you're looking for array_merge, which merges two arrays together:
$new_arr = array_merge($arr['jobDescription'], $arr['userDetail']);
array_merge($bigArray['jobDescription'], $bigArray['userDetail']);
You only need to loop once. No need for nesting. This solution covers where you have an undefined number of arrays to combine. Otherwise, you can use array_merge as suggested by Dickie
$allValues = array();
if(count($mainArray) > 0)
{
foreach($mainArray as $arr)
{
$allValues += $arr;
}
}
The array_merge() function can create an array from multiple arrays. In your example, it works this way:
$yours = array(...);
$values = array_merge($yours["jobDescription"], $yours["userDetail"]);

Categories