NULL to 0 - PHP array - php

I have an Array that contains some entries. Some are string other are int. and those are defined in MySQL with type (int, varchar). The array i create looks like this: (minified the array because too long)
[3] => Array
(
[account_id] => *******
[month_id] => 201903
[month_comment] => 4,5% spend flat
[month_spend] => 23000
[month_budget] => 0
[month_adops] => 1035
[month_adops_forecast] => 1035
)
[4] => Array
(
[account_id] => ******
[month_id] => 201905
[month_comment] =>
[month_spend] =>
[month_budget] => 0
[month_adops] =>
[month_adops_forecast] => 45
)
[5] => Array
(
[account_id] => *******
[month_id] => 201906
[month_comment] =>
[month_spend] =>
[month_budget] => 0
[month_adops] =>
[month_adops_forecast] => 92
)
As you can see some of "month_spend" and/or "month_adops" is empty, the problem is that in PHP the value is converted to "NULL" when the field is Integer in database, so result gives me:
Incorrect integer value: '' for column 'month_spend' at row 2"
So i tried to change this inside an foreach loop like this:
$result_replace = array();
foreach ($data_replace as $key => $result) {
$result['month_id'] = substr_replace($result['month_id'], '2019', 0, 4);
if(empty($result['month_budget'])) {
$result['month_budget'] = 0;
$result_replace[] = $result;
}
else if(empty($result['month_spend'])) {
$result['month_spend'] = 0;
$result_replace[] = $result;
}
}
but looks like the foreach loop does not edit the data?

Use following to check both instead of else if
$result_replace = array();
foreach ($data_replace as $key => &$result) {
$result['month_id'] = substr_replace($result['month_id'], '2019', 0, 4);
if(empty($result['month_budget'])) {
$result['month_budget'] = 0;
}
if(empty($result['month_spend'])) {
$result['month_spend'] = 0;
}
$result_replace[] = $result;
}

Try replacing
empty()
by
is_null()

assumin your array is name $myArray
foreach ($myArray as $key => $result) {
if(empty($result['month_budget'])) {
$myArray[$key]['month_budget'] = 0
}
if(empty($result['month_spend'])) {
$myArray[$key]['month_spend'] = 0
}
}
var_dump($myArray)
in your case you are just assignt an empty array to $result_replace nothing else

empty from 0 will return false. So your code will be redundant with this function. Try to use is_integer. If not integer assign zero. The bad part is that you cannot avoid the loop with foreach.
is it possible to avoid the foreach from php by using a more concrete mysql query with e.g. IF(ISNULL(your_column), 0, your_column).

array_walk_recursive($array, function (&$value, $key){
if(!isset($value) && ('month_spend' === $key || 'month_adops' === $key)) {
$value = 0;
}
});

Related

Change multidimensional array value with wildcard in php?

So say I have an array below. As an example, is it possible in PHP to replace the -2.7 value of the first array part to 100 without knowing the #RR key or #BR for the other part? Such as:
$array[8314][WILDCARD][-1] = 100;
Array
(
[8314] => Array
(
[#RR] => Array
(
[-1] => -2.7
[0] => 0
)
)
[8810] => Array
(
[#BR] => Array
(
[-1] => 32500
[0] => 0
)
)
)
I think that you are looking for the below solution using array_key_first:
$firstKey = array_key_first($array); //say we found 8314;
$WILDCARD = array_key_first($array[$firstKey]);
//replace the old value with 100;
$array[$firstKey][$WILDCARD][-1] = 100;
Yes:
foreach ($input as $outerKey => $outerValue) {
foreach ($outerValue as $innerKey => $innerValue) {
foreach ($innerValue as $key => $value) {
if ($value === 2.7) $input[$outerKey][$innerKey][$key] = 100;
}
}
}
The code above assumes that you want to change 2.7 => 100 for all elements. If, instead of that you need to do it just for the first, then:
$visited = false;
foreach ($outerValue as $innerKey => $innerValue) {
if ($visited) break;
$visited = true;
foreach ($innerValue as $key => $value) {
if ($value === 2.7) $input[$outerKey][$innerKey][$key] = 100;
}
}

Remove element from multidimensional indexed array by value using PHP

I have array:
Array
(
[5] => Array
(
[0] => 19
[1] => 18
)
[6] => Array
(
[0] => 28
)
)
And I'm trying to delete element by value using my function:
function removeElementWithValue($obj, $delete_value){
if (!empty($obj->field)) {
foreach($obj->field as $key =>$value){
if (!empty($value)) {
foreach($value as $k=>$v){
if($v == $delete_value){
$obj->field[$key][$k] = '';
}
}
}
}
}
return urldecode(http_build_query($obj->field));
}
echo removeElementWithValue($request, '19');
After operation above I have: 5[0]=&5[1]=18&6[0]=28; // Right!!!
echo removeElementWithValue($request, '18');
After operation above I have: 5[0]=&5[1]=&6[0]=28; // Wrong ???
But my expected result after second operation is:
5[0]=19&5[1]=&6[0]=28;
Where is my mistake?
Thanks!
Use array_walk_recursive to find and change value
$arr = Array (
5 => Array ( 0 => 19, 1 => 18 ),
6 => Array ( 0 => 28));
$value = 18;
array_walk_recursive($arr,
function (&$item, $key, $v) { if ($item == $v) $item = ''; }, $value);
print_r($arr);
result:
Array (
5 => Array ( 0 => 19, 1 => ),
6 => Array ( 0 => 28));
A simpler function might be..
function removeElementWithValue($ar,$val){
foreach($ar as $k=>$array){
//update the original value with a new array
$new_ar = array_diff_key($array,array_flip(array_keys($array,$val)));
if($new_ar){
$ar[$k]=$new_ar;
}else{
unset($ar[$k]);//or remove the empty value
}
}
return $ar;
}

PHP: How can I get the value from a key in a multiple array

The multiple array looks like
Array
(
[id] => description
[header] =>
[width] => 20
[dbfield] => description
[type] => text
)
Array
(
[id] => quantity
[header] => Menge
[dbfield] => QUANTITY_NEW
[width] => 60
[type] => decimal
)
How can I get the value from dbfield where id is 'quantity' without knowing the numeric value of the id?
The actual code looks like
foreach($array as $id => $fieldData) {
if($fieldData['type'] == 'decimal')
{
doSomething...();
}
}
In the part with doSomething I need access to other fields from the array, but I only know the id. I already tried it with dbfield['quantity']['dbfield'] etc. which obviously fails.
A simple alternative using array_keys:
function getValues($data, $lookForValue, $column)
{
$res = array();
foreach ($data as $key => $data)
{
if($idx = array_keys($data, $lookForValue))
{
$res[$idx[0]] = $data[$column];
}
}
return $res;
}
$values = getValues($myData, "quantity", "dbfield");
var_dump($values);
echo out the array as such..
$array = array();
$array['qty'] = 'qtty';
$array['dbfield'] = 'QUANTITY_NEW';
if($array['qty'] = 'qtty'){
echo $array['dbfield'];
}
returns - QUANTITY_NEW
You can do this with several methods, one of them is using array_map to get those values:
$dbfield = array_filter(array_map(function($a){
if($a["id"] === "quantity"){
return $a["dbfield"];
}
}, $array));
print_r($dbfield);
You iterate over the array, and return the key dbfield where id is 'quantity'. Array filter is just to not return null values where it doesn't have 'quantity' id.
Online attempt to reproduce your code can be found here

Replacing values in the array nvp

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;

need to search for values in each string of an array to construct another array

I have this array:
Array
(
[count] => 12
[6] => CN=G_Information_Services,CN=Users,DC=hccc,DC=campus
[7] => CN=WEBadmin,CN=Users,DC=hccc,DC=campus
[9] => CN=G_ISDept,CN=Users,DC=hccc,DC=campus
[10] => CN=STAFF,CN=Users,DC=hccc,DC=campus
)
and I want to create an array of values that consist of the value between the first CN= and , of each array value below.
I probably will have to loop thru the array above, do a regex search for the first occurrence of cn and the value that follows it
I am not sure what I am doing wrong.
I need the final result to be an array that resembles this:
array('G_Information_Services', 'WEBadmin', 'G_ISDept', 'STAFF');
Use preg_match on each of the array values to get only the first corresponding CN value.
$found = array();
foreach ($arr AS $values) {
if (preg_match('/CN=([^,]+),/',$values,$matches))
$found[] = $matches[1];
}
Output
Array
(
[0] => G_Information_Services
[1] => WEBadmin
[2] => G_ISDept
[3] => STAFF
)
Try this (not the most efficient way but it should work):
foreach ($array as $key => $value)
{
if (is_numeric($key))
{
$array[$key] = explode(',', $array[$key]);
$array[$key] = $array[$key][0];
$array[$key] = substr($array[$key], 3);
}
}
This gets the first value of CN= of each element of the array, it also ignores any DC= values.
$arr = array(
'count' => 12,
6 => 'CN=G_Information_Services,CN=Users,DC=hccc,DC=campus',
7 => 'CN=WEBadmin,CN=Users,DC=hccc,DC=campus',
9 => 'CN=G_ISDept,CN=Users,DC=hccc,DC=campus',
10 => 'CN=STAFF,CN=Users,DC=hccc,DC=campus'
);
$newArr = array();
foreach($arr as $key => $value)
{
if($key != 'count')
{
$temp = explode(',', $value);
foreach($temp as $item)
{
if(strpos($item, 'CN=') === 0)
{
$item = substr($item, 3 );
$newArr[] = $item;
break 1;
}
}
}
}
print_r($newArr);

Categories