Replacing values in the array nvp - php

I have been trying to replace the values in the array
I'll name this array as $currencies when i print this it looks like.
Array
(
[0] => Array
(
[currencylabel] => USA, Dollars
[currencycode] => USD
[currencysymbol] => $
[curid] => 1
[curname] => curname1
[check_value] =>
[curvalue] => 0
[conversionrate] => 1
[is_basecurrency] => 1
)
[1] => Array
(
[currencylabel] => India, Rupees
[currencycode] => INR
[currencysymbol] => ₨
[curid] => 2
[curname] => curname2
[check_value] =>
[curvalue] => 0
[conversionrate] => 50
[is_basecurrency] =>
)
[2] => Array
(
[currencylabel] => Zimbabwe Dollars
[currencycode] => ZWD
[currencysymbol] => Z$
[curid] => 3
[curname] => curname3
[check_value] =>
[curvalue] => 0
[conversionrate] => 22
[is_basecurrency] =>
)
)
Here I am having a $conversionRate to which i need to divide the values present in the array $currencies [0] -> Array -> [conversionrate] and replace in the same place in array.
and the same operation for [1] -> Array -> [conversionrate] and so on..
for which my current approach is as follows
$conversionRate = 50;
foreach ($currencies as $key => $val) {
$key['conversionrate'] = $key['conversionrate'] / $conversionRate;
if($key['conversionrate'] == 1) {
$key['is_basecurrency'] = 1;
} else {
$key['is_basecurrency'] = '';
}
}
print_r($key);
die;
Currently this is not working kindly help

Your loop is all wrong, there is no $key['conversionrate'], it's $val['conversionrate']. In fact there doesn't seems to be a reason for the $key variable, you can just loop through the array with
foreach ($currencies as &$val)
Also, you probably want to print_r($currencies), not $key

Do not compare floating point numbers with == to 1, it might not work due to rounding errors.
You mixed up key and value and you need to use &$val to be able to change the array.
$conversionRate = 4;
foreach ($currencies as $key => &$val) {
if($val['conversionrate'] == $conversionRate) {
$val['is_basecurrency'] = 1;
} else {
$val['is_basecurrency'] = '';
}
$val['conversionrate'] = $val['conversionrate'] / $conversionRate;
}
unset($val);
print_r($currencies);
die;

$key is an index identofoer of an array and $val contain array values
so use like this
$conversionRate = 4;
foreach ($currencies as $key => $val) {
$val['conversionrate'] = $val['conversionrate'] / $conversionRate;
if($val['conversionrate'] == 1) {
$val['is_basecurrency'] = 1;
} else {
$val['is_basecurrency'] = '';
}
}
print_r($val);
die;

Related

how to filter multidimensional array. php

I have some confusing issue here. please take a look and help if you don't mind.
let's say i have this multidimensional array, called $array.
[1] => Array
(
[3] => 2
[2] => 5
[4] => 4
)
[3] => Array
(
[1] => 2
)
[2] => Array
(
[1] => 5
)
that array is representing a path between two node. I try to implmenting dijkstra algorhitm here. when it's
$array[1][2] = 5
that's mean the distance between node 1 to node 2 is 5 and so on.
what Im asking is, how can I detect that array $array[1][4] = 4 doesn't have a reverse path such $array[4][1] = 4 like the example above.
thank you in advance.
Follow this:
$temp = array();
$array = array('1' => Array
(
'3' => 2,
'2' => 5,
'4' => 4
),
'3' => Array
(
'1' => 2
),
'2' => Array
(
'1' => 5
));
foreach ($array as $key => $value)
{
foreach ($value as $k => $v)
{
if($array[$key][$k] == isset($array[$k][$key]))
{
echo $key . 'to' . $k . 'reverse path available';
echo "<br>";
}
}
}
Like this.Loop foreach inside another foreach and check based on keys.
$array = array('1'=>array('3'=>2),'3'=>array('1'=>2));//assumed reversed array
//print_r($array);
foreach($array as $key=>$value){
foreach($value as $k=>$v){
if($array[$key][$k] == $array[$k][$key]){
echo "Reverse at:array[".$key."][".$k."]".PHP_EOL;
continue;
}
}
}
Output:
Reverse at:array[1][3]
Reverse at:array[3][1]
for that array you have to add nested for loop..
for($i=0;$i<count($your_array);$i++)
{
for($j=0;$j<count($your_array[$i]);$j++)
{
if(isset($your_array[$i][$j]) && isset($your_array[$j][$i]) && $your_array[$i][$j]==$your_array[$j][$i])
{
echo "same distance";
}
else
{
echo "different distance or path not available";
}
}
}

PHP Count Duplicate Total Link

how can i count the total duplicate link in the array?
its similar question here: count of duplicate elements in an array in php
but im not sure how to implement the code on my case.
my server PHP version 5.4
Array
(
[0] => Array
(
[link] => http://myexample.com
[total] => 3
)
[1] => Array
(
[link] => http://myexampledomain.com
[total] => 2
)
[2] => Array
(
[link] => http://myexample.com
[total] => 1
)
)
I am expecting the result to be:
http://myexample.com: 4
http://myotherdomain.com: 2
You can simply use
$result = [];
array_walk($arr, function($v, $k)use(&$result) {
if (isset($result[$v['link']])) {
$result[$v['link']] += $v['total'];
}else{
$result[$v['link']] = $v['total'];
}
});
print_r($result);
Demo
Try below code:
<?php
$array = array(array("link" => "http://myexample.com", "total" => 3), array("link" => "http://myexampledomain.com", "total" => 2), array("link" => "http://myexample.com", "total" => 1));
$res = array();
foreach ($array as $vals) {
if (array_key_exists($vals['link'], $res)) {
$res[$vals['link']]+=$vals['total'];
} else {
$res[$vals['link']]=$vals['total'];
}
}
print_r($res);
?>
You can use this simple logic :
$tempArray = array();
foreach ($array as $value) {
if (!array_key_exists($value['link'],$tempArray) {
$tempArray[$value['link']] = 1;
} else {
$tempArray[$value['link']] = $tempArray['link'] + 1;
}
}
print_r($tempArray);

Foreach Value in Array Check to see if that value is Greater than any value in another Array

I have two arrays which the key is a [part id]. The value is record => Qty:Length. I want to be able to check if any of the values under the same part id from the sencond array is greater than the length of the first array. For example the Part id 2099 in the second array has a qty:length of 14:11.25 and that is greater than the 6:3.33 which I want that to return true in PHP. I Have a function to split up the qty and length but after that I am unsure where to go. It returns "Warning: explode() expects parameter 2 to be string," Any Help Appreciated.
Array
(
[2099] => Array
(
[360] => 6:3.33
[362] => 14:8.75
)
[2130] => Array
(
[361] => 4:2.5
)
)
Array
(
[2099] => Array
(
[360] => 12:8.33
[362] => 14:11.25
)
[2130] => Array
(
[361] => 24:3.5
)
)
My PHP:
foreach ($a as $partid=>$qty_length){
$ex_part = explode(":", $qty_length);
}
You can do a nested foreach loop to find the difference
<?php
$array1 = array(2099 => array(360 => "6:3.33",362 => "14:8.75"),2130 => array(361 => "4:2.5"));
$array2 = array(2099 => array(360 => "12:8.33",362 => "14:11.25"),2130 => array(361 => "24:3.5"));
foreach($array1 as $key => $value)
{
foreach ($value as $key1 => $value1) {
// $array1[$key][$key1] get the value of array one curreny key
// $array2[$key][$key1] get the value of array two current key
$one = explode(':',$array1[$key][$key1]); // array one value e.g 360 => "6:3.33"
$two = explode(':',$array2[$key][$key1]); // array two value e.g 360 => "12:8.33"
// do what ever you want here
if($one[0] > $two[0])
{
echo "array one key " . $key1 . " is bigger <br>";
}else{
echo "array two key " . $key1 . " is bigger <br>";
}
}
}
$arr =Array
(
'2099' => Array
(
'360' => '6:3.33',
'362' => '14:8.75'
),
'2130' => Array
(
'361' => '4:2.5'
),
'2131' => Array
(
'362' => '24:3.5'
)
);
$arr1=Array
(
'2099' => Array
(
'360' => '12:8.33',
'362' => '14:11.25'
),
'2130' => Array
(
'361' => '24:3.5'
),
'2131' => Array
(
'362' => '20:3.5'
)
);
foreach ($arr as $partid=>$qty_length){
foreach($qty_length as $key=>$val){
$ex_part = explode(":", $val);
// print_r($ex_part);
$ex_part1 = $arr1[$partid];
$len = sizeof($ex_part1);
foreach( $ex_part1 as $key1=>$val1){
$ex_part1 = explode(":", $arr1[$partid][$key1]);
if($ex_part[0] < $ex_part1[0] && $ex_part[1] < $ex_part1[1]){
$len--;
if($len == 0){
echo $ex_part1[0]."<br>";
}else{
continue;
}
}else if($ex_part[0] >= $ex_part1[0] && $ex_part[1] >= $ex_part1[1]){
$len--;
if($len == 0){
echo $ex_part[0]."else <br>";
}else{
continue;
}
}
}
}
}
you can add more conditions also.

How to get particular array value in php?

I have the following $qtips_messages array,
Array
(
[0] => Array
(
[id] => 1
[tips_title] => email_tips
[tips_message] => ex:xxxxx#xyz.com
[tips_key] => key_email
)
[1] => Array
(
[id] => 2
[tips_title] => website_tips
[tips_message] => ex:http://www.yahoo.co.in
[tips_key] => key_website
)
[2] => Array
(
[id] => 3
[tips_title] => zipcode_tips
[tips_message] => ex:60612
[tips_key] => key_zipcode
)
[3] => Array
(
[id] => 4
[tips_title] => phone_tips
[tips_message] => ex:1234567890
[tips_key] => key_phone
)
)
For example, I want to get the tips message for the tip_title 'email_tips'
I have tried with following code,
foreach($qtips_messages as $qtipsArray){
foreach($qtipsArray as $qkey=>$qvalue){
if($qtipsArray['tips_title'] == 'email_tips'){
$emailtipsMessage = $qtipsArray['tips_message'];
}
}
}
When i ran the above code i did not get any value.
What is wrong with this code?
You only need one loop:
$message = null;
foreach ($array as $tips) {
if ($tips['tips_title'] == 'email_tips') {
$message = $tips['tips_message'];
break;
}
}
I'd probably go for something like this though:
$message = current(array_filter($array, function ($tip) { return $tip['tips_title'] == 'email_tips'; }));
echo $message['tips_message'];
$array = array();
foreach($result AS $k =>$val)
$array[$val['tips_key']] = $val['tips_message'];
return $array;
Now the array $array have all the values for q-tips based on their keys...
Hope this will helps you...
try this way.
$array = array();
foreach($qtips_messages AS $k =>$val):
if($val['tips_title']=='email_tips')
{
$array[$val['tips_key']] = $val['tips_message'];
print_r($array);
break;
}
endforeach;

parsing out the last number of the post

Ok so i have a post that looks kind of this
[optional_premium_1] => Array
(
[0] => 61
)
[optional_premium_2] => Array
(
[0] => 55
)
[optional_premium_3] => Array
(
[0] => 55
)
[premium_1] => Array
(
[0] => 33
)
[premium_2] => Array
(
[0] => 36 )
[premium_3] => Array
(
[0] => 88 )
[premium_4] => Array
(
[0] => 51
)
how do i get the highest number out of the that. So for example, the optional "optional_premium_" highest is 3 and the "premium_" optional the highest is 4. How do i find the highest in this $_POST
You could use array_key_exists(), perhaps something like this:
function getHighest($variableNamePrefix, array $arrayToCheck) {
$continue = true;
$highest = 0;
while($continue) {
if (!array_key_exists($variableNamePrefix . "_" . ($highest + 1) , $arrayToCheck)) {
$continue = false;
} else {
highest++;
}
}
//If 0 is returned than nothing was set for $variableNamePrefix
return $highest;
}
$highestOptionalPremium = getHighest('optional_premium', $_POST);
$highestPremium = getHighest('premium', $_POST);
I have 1 question with 2 parts before I answer, and that is why are you using embedded arrays? Your post would be much simpler if you used a standard notation like:
$_POST['form_input_name'] = 'whatever';
unless you are specifically building this post with arrays for some reason. That way you could use the array key as the variable name and the array value normally.
So given:
$arr = array(
"optional_premium_1" => "61"
"optional_premium_2" => "55"
);
you could use
$key = array_keys($arr);
//gets the keys for that array
//then loop through get raw values
foreach($key as $val){
str_replace("optional_premium_", '', $val);
}
//then loop through again to compare each one
$highest = 0;
for each($key as $val){
if ((int)$val > $highest) $highest = (int)$val;
}
that should get you the highest one, but then you have to go back and compare them to do whatever your end plan for it was.
You could also break those into 2 separate arrays and assuming they are added in order just use end() http://php.net/manual/en/function.end.php
Loop through all POST array elements, pick out elements having key names matching "name_number" pattern and save the ones having the largest number portion of the key names. Here is a PHP script which does it:
<?php // test.php 20110428_0900
// Build temporary array to simulate $_POST
$TEMP_POST = array(
"optional_premium_1" => array(61),
"optional_premium_2" => array(55),
"optional_premium_3" => array(55),
"premium_1" => array(33),
"premium_2" => array(36),
"premium_3" => array(88),
"premium_4" => array(51),
);
$names = array(); // Array of POST variable names
// loop through all POST array elements
foreach ($TEMP_POST as $k => $v) {
// Process only elements with names matching "word_number" pattern.
if (preg_match('/^(\w+)_(\d+)$/', $k, $m)) {
$name = $m[1];
$number = (int)$m[2];
if (!isset($names[$name]))
{ // Add new POST var key name to names array
$names[$name] = array(
"name" => $name,
"max_num" => $number,
"key_name" => $k,
"value" => $v,
);
} elseif ($number > $names[$name]['max_num'])
{ // New largest number in key name.
$names[$name] = array(
"name" => $name,
"max_num" => $number,
"key_name" => $k,
"value" => $v,
);
}
}
}
print_r($names);
?>
Here is the output from the script:
Array
(
[optional_premium] => Array
(
[name] => optional_premium
[max_num] => 3
[key_name] => optional_premium_3
[value] => Array
(
[0] => 55
)
)
[premium] => Array
(
[name] => premium
[max_num] => 4
[key_name] => premium_4
[value] => Array
(
[0] => 51
)
)
)
Though ineffective, you could try something like
$largest = 0;
foreach($_POST as $key => $value)
{
$len = strlen("optional_premium_");
$num = substr($key, $len);
if($num > $largest)
$largest = $num;
}
print_r($largest);
The problem being that this will only work for one set of categories. It will most likely give errors throughout the script.
Ideally, you would want to reorganize your post, make each array be something like
[optional_premium_1] => Array
(
[0] => 61
["key"] => 1
)
[optional_premium_2] => Array
(
[0] => 61
["key"] => 2
)
Then just foreach and use $array["key"] to search.

Categories