How to change array value from string to integer - php

I have the following array and I would like to change each [Entry] value from a string to an integer:
Array ( [0] => Array ( [Time] => 06:08:00 [Entry] => 250 ) [1] => Array ( [Time] => 08:08:00 [Entry] => 230 )
I am trying in this manner, which seems to change the type within the loop but the change does not seem to take effect outside the loop. I'm new at this, so I'm probably overlooking something, and most likely a simpler way to accomplish this.
foreach($data as $inner) {
foreach($inner as $key=>$val) {
if($key == 'Entry') {
$newval = intval($val);
$val = $newval;
echo(gettype($val));//integer
}
}
}
echo(gettype($data[0]['Entry'])); //string

You are not changing the Value of the element in the array.
foreach($data as &$inner) {
$inner['Entry'] = intval($inner['Entry']);
}
To modify the array elements within the loop, you have to precede $inner with &. i.e. The value will be assigned by reference.
For details see foreach

You need to re-cast it to the actual array.
foreach($data as $dkey => $inner) {
foreach($inner as $ikey => $val) {
if ($ikey == 'Entry') {
$data[$dkey][$ikey] = intval($val);
}
}
}

Related

How can I sort values from an existing array by data type?

I try to determine the data type of each array value from an existing array using foreach() and var_dump().
Let's say I have this array: example:
$arr = ['this','is', 1, 'array', 'for', 1, 'example'];
Now I have to take each value of this field and determine its data type.
I try this:
$str = array();
$int = array();
foreach($arr as $k => $val) {
if(var_dump($arr[$k]) == 'string'){
$str[] = $arr[$k];
} else {
$int[] = $arr[$k];
}
}
In other words, I try to sort the values from an existing array by data type and create a new array with only 'string' values and a second new array with only 'int' values. But it seems that my 'if' condition isn't working properly. How else could I solve this please? Thank you.
You need to use gettype to get the type of a value, not var_dump:
foreach($arr as $k => $val) {
if(gettype($arr[$k]) == 'string'){
$str[] = $arr[$k];
} else {
$int[] = $arr[$k];
}
}
Output:
Array
(
[0] => this
[1] => is
[2] => array
[3] => for
[4] => example
)
Array
(
[0] => 1
[1] => 1
)
Demo on 3v4l.org
Use gettype
$data = array('this','is', 1, 'array', 'for', 1, 'example');
foreach ($data as $value) {
echo gettype($value), "\n";
}

php - Multidimensional Array To Single dimension Array With Sum Up

I have this array:
Array
(
[one] => Array
(
[a] => 0
[b] => 1
[c] => 1
[d] => 3
[e] => 1
)
[two] => Array
(
[a] => 0
[b] => 3
[c] => 1
[d] => 4
[e] => 1
)
[three] => Array
(
[a] => 3
[b] => 1
[c] => 2
[d] => 4
[e] => 1
)
)
And I want to convert it into single array with the values are the sums of every value inside the inner array, so it could be like this:
Array
(
[a] => 3
[b] => 5
[c] => 4
[d] => 11
[e] => 3
)
How to achieve it?
EDIT
This was the best what I've done:
$rest = array();
foreach($result as $key => $value){
if(is_array($value)) {
foreach($value as $k => $val){
$rest[$k] = array_sum($value);
}
}
}
But it returns all values to be the same, i.e all 9 on every inner key.
You can get the keys from the first child array with array_keys, and then use array_sum and array_column to generate the array of sums.
foreach (array_keys($your_array['one']) as $key) {
$sums[$key] = array_sum(array_column($your_array, $key));
}
array_column does require php >= 5.5.
Incidentally, what you already had was really close to working. If you change
$rest[$k] = array_sum($value);
to
$rest[$k] += $val;
It should be good to go. What you had before was repeatedly summing the entire sub-array and assigning it to each letter key, but you just needed to add the current value to that letter key.
$rest[$k] += $val; will work, but give you undefined index notices for the first sub-array. You can fix that by checking isset before assigning, like this:
$rest[$k] = isset($rest[$k]) ? $rest[$k] + $val : $val;
I would say modifying your original code to work this way would probably be better than redefining array_column if you can't use it.
You have multidimensional Array , that why have to use two loop for understanding in beginning level. First loop will get Every Object of Array , Second Array will get the Params of Object.
$finalArray = array();
for($i = 0;$i<count($array);$i++){ // GET ALL OBJECT FROM ARRAY
foreach($array[$i] as $key=>$value){ // GET ALL KEY FROM OBJECT
$finalArray[$key] += $array[$i][$key];
}
}
print_r($finalArray);
Work on all version of PHP
You can use array_sum and loop over the first dimension
foreach ($array as $key => $values) {
$newArray[$key] = array_sum($values);
}
Credit to Don't Panic's answer above and this answer which is providing array_column() alternative for PHP version < 5.5
// if array_column function don't exist, add array_column function
if (! function_exists('array_column')) {
function array_column(array $input, $columnKey, $indexKey = null) {
$array = array();
foreach ($input as $value) {
if ( ! isset($value[$columnKey])) {
trigger_error("Key \"$columnKey\" does not exist in array");
return false;
}
if (is_null($indexKey)) {
$array[] = $value[$columnKey];
}
else {
if ( ! isset($value[$indexKey])) {
trigger_error("Key \"$indexKey\" does not exist in array");
return false;
}
if ( ! is_scalar($value[$indexKey])) {
trigger_error("Key \"$indexKey\" does not contain scalar value");
return false;
}
$array[$value[$indexKey]] = $value[$columnKey];
}
}
return $array;
}
}
// sum up the values
$rest = array();
foreach($result as $key => $arr){
if(is_array($arr)) {
foreach($arr as $k => $val){
$rest[$k] = array_sum(array_column($result, $k));
}
}
}

How to get a value from an array

Not sure why I can't this to work. My json is:
[values] => Array
(
[0] => Array
(
[field] => id1
[value] => 985
)
[1] => Array
(
[field] => id2
[value] => 6395
)
[2] => Array
(
[field] => memo
[value] => abcde
)
I simply want the values of id2
I tried:
foreach ($json['values'] as $values) {
foreach ($json as $key=>$data) {
if ($data['field'] == 'id2') {
$result = $data['value'];
print '<br>value: '.$result;
}
}
}
Thanks. I know this should be relatively simple and I'm sure I've done this correctly before.
there's no need for inner loop, after the first one $values already contain the exact array that you are looking for
foreach ($json['values'] as $values) // $values contain
{
if ($values['field'] == 'id2')
{
$result = $values['value'];
print '<br>value: '.$result;
}
}
foreach ($json['values'] as $values) { //you're looping your first array, puttin each row in a variable $values
foreach ($values as $key=>$data) { //you're looping inside values taking the array index $key and the value inside that index $data
if ($key == 'id2') { //test if $key (index) is = to id2
print '<br>value: '.$value; // print the value inside that index
}
}
}
this is just an explanation, to what is going wrong with your code, but as #Pawel_W there is no need for the second foreach loop you can directly test
if($values['field']=='id2'){ print $values['value'];}
I think you just need to use array_search.
And here is recursive array_search ;
Assuming there might be multiple fields with the same name and you want them all as array, here's an alternative take:
array_filter(array_map(function($item) { return $item['field'] == 'id2' ? $item['value'] : null; }, $json['values']));
If your field names are always unique and you just want a single scalar:
array_reduce($json['values'], function($current, $item) { return $item['field'] == 'id2' ? $item['value'] : $current; });
(note that this one is not ideal since it will walk all the array even if match is found in first element)
And here's a gist with both in this and function form + output.

Replace key of array with the value of another array while looping through

I have two multidimensional arrays. First one $properties contains english names and their values. My second array contains the translations. An example
$properties[] = array(array("Floor"=>"5qm"));
$properties[] = array(array("Height"=>"10m"));
$translations[] = array(array("Floor"=>"Boden"));
$translations[] = array(array("Height"=>"Höhe"));
(They are multidimensional because the contains more elements, but they shouldn't matter now)
Now I want to translate this Array, so that I its at the end like this:
$properties[] = array(array("Boden"=>"5qm"));
$properties[] = array(array("Höhe"=>"10m"));
I have managed to build the foreach construct to loop through these arrays, but at the end it is not translated, the problem is, how I tell the array to replace the key with the value.
What I have done is this:
//Translate Array
foreach ($properties as $PropertyArray) {
//need second foreach because multidimensional array
foreach ($PropertyArray as $P_KiviPropertyNameKey => $P_PropertyValue) {
foreach ($translations as $TranslationArray) {
//same as above
foreach ($TranslationArray as $T_KiviTranslationPropertyKey => $T_KiviTranslationValue) {
if ($P_KiviPropertyNameKey == $T_KiviTranslationPropertyKey) {
//Name found, save new array key
$P_KiviPropertyNameKey = $T_KiviTranslationValue;
}
}
}
}
}
The problem is with the line where to save the new key:
$P_KiviPropertyNameKey = $T_KiviTranslationValue;
I know this part is executed correctly and contains the correct variables, but I believe this is the false way to assing the new key.
This is the way it should be done:
$properties[$oldkey] = $translations[$newkey];
So I tried this one:
$PropertyArray[$P_KiviPropertyNameKey] = $TranslationArray[$T_KiviTranslationPropertyKey];
As far as I understood, the above line should change the P_KiviPropertyNameKey of the PropertyArray into the value of Translation Array but I do not receive any error nor is the name translated. How should this be done correctly?
Thank you for any help!
Additional info
This is a live example of the properties array
Array
(
[0] => Array
(
[country_id] => 4402
)
[1] => Array
(
[iv_person_phone] => 03-11
)
[2] => Array
(
[companyperson_lastname] => Kallio
)
[3] => Array
(
[rc_lot_area_m2] => 2412.7
)
[56] => Array
(
[floors] => 3
)
[57] => Array
(
[total_area_m2] => 97.0
)
[58] => Array
(
[igglo_silentsale_realty_flag] => false
)
[59] => Array
(
[possession_partition_flag] => false
)
[60] => Array
(
[charges_parkingspace] => 10
)
[61] => Array
(
[0] => Array
(
[image_realtyimagetype_id] => yleiskuva
)
[1] => Array
(
[image_itemimagetype_name] => kivirealty-original
)
[2] => Array
(
[image_desc] => makuuhuone
)
)
)
And this is a live example of the translations array
Array
(
[0] => Array
(
[addr_region_area_id] => Maakunta
[group] => Kohde
)
[1] => Array
(
[addr_town_area] => Kunta
[group] => Kohde
)
[2] => Array
(
[arable_no_flag] => Ei peltoa
[group] => Kohde
)
[3] => Array
(
[arableland] => Pellon kuvaus
[group] => Kohde
)
)
I can build the translations array in another way. I did this like this, because in the second step I have to check, which group the keys belong to...
Try this :
$properties = array();
$translations = array();
$properties[] = array("Floor"=>"5qm");
$properties[] = array("Height"=>"10m");
$translations[] = array("Floor"=>"Boden");
$translations[] = array("Height"=>"Höhe");
$temp = call_user_func_array('array_merge_recursive', $translations);
$result = array();
foreach($properties as $key=>$val){
foreach($val as $k=>$v){
$result[$key][$temp[$k]] = $v;
}
}
echo "<pre>";
print_r($result);
output:
Array
(
[0] => Array
(
[Boden] => 5qm
)
[1] => Array
(
[Höhe] => 10m
)
)
Please note : I changed the array to $properties[] = array("Floor"=>"5qm");, Removed a level of array, I guess this is how you need to structure your array.
According to the structure of $properties and $translations, you somehow know how these are connected. It's a bit vague how the indices of the array match eachother, meaning the values in $properties at index 0 is the equivalent for the translation in $translations at index 0.
I'm just wondering why the $translations array need to have the same structure (in nesting) as the $properties array. To my opinion the word Height can only mean Höhe in German. Representing it as an array would suggest there are multiple translations possible.
So if you could narrow down the $translations array to an one dimensional array as in:
$translation = array(
"Height"=>"Höhe",
"Floor"=>"Boden"
);
A possible loop would be
$result = array();
foreach($properties as $i => $array2) {
foreach($array2 as $i2 => $array3) {
foreach($array3 as $key => $value) {
$translatedKey = array_key_exists($key, $translations) ?
$translations[$key]:
$key;
$result[$i][$i2][$translatedKey] = $value;
}
}
}
(I see every body posting 2 loops, it's an array,array,array structure, not array,array ..)
If you cannot narrow down the translation array to a one dimensional array, then I'm just wondering if each index in the $properties array matches the same index in the $translations array, if so it's the same trick by adding the indices (location):
$translatedKey = $translations[$i][$i2][$key];
I've used array_key_exists because I'm not sure a translation key is always present. You have to create the logic for each case scenario yourself on what to check or not.
This is a fully recursive way to do it.
/* input */
$properties[] = array(array("Floor"=>"5qm", array("Test"=>"123")));
$properties[] = array(array("Height"=>"10m"));
$translations[] = array(array("Floor"=>"Boden", array("Test"=>"Foo")));
$translations[] = array(array("Height"=>"Höhe"));
function array_flip_recursive($arr) {
foreach ($arr as $key => $val) {
if (is_array($val)) {
$arr[$key] = array_flip_recursive($val);
}
else {
$arr = #array_flip($arr);
}
}
return $arr;
}
function array_merge_it($arr) {
foreach ($arr as $key => $val) {
if (is_array($val)) {
$arr[$key] = array_merge_it($val);
} else {
if(isset($arr[$key]) && !empty($arr[$key])) {
#$arr[$key] = $arr[$val];
}
}
}
return $arr;
}
function array_delete_empty($arr) {
foreach ($arr as $key => $val) {
if (is_array($val)) {
$arr[$key] = array_delete_empty($val);
}
else {
if(empty($arr[$key])) {
unset($arr[$key]);
}
}
}
return $arr;
}
$arr = array_replace_recursive($properties, $translations);
$arr = array_flip_recursive($arr);
$arr = array_replace_recursive($arr, $properties);
$arr = array_merge_it($arr);
$arr = array_delete_empty($arr);
print_r($arr);
http://sandbox.onlinephpfunctions.com/code/d2f92605b609b9739964ece9a4d8f389be4a7b81
You have to do the for loop in this way. If i understood you right (i.e) in associative array first key is same (some index).
foreach($properties as $key => $values) {
foreach($values as $key1 => $value1) {
$propertyResult[] = array($translations[$key][$key1][$value1] => $properties[$key][$key1][$value1]);
}
}
print_r($propertyResult);

how to reach into PHP nested arrays?

I've a nested array whose print_r looks like this-
Array
(
[keyId] => Array
(
[hostname] => 192.168.1.127
[results] => Array
(
[1] => false
[2] => false
[3] => false
)
[sessionIDs] => Array
(
[0] => ed9f79e4-2640-4089-ba0e-79bec15cb25b
)
)
I would like to process(print key and value) of the "results" array. How do I do this?
I am trying to use array_keys function to first get all the keys and if key name is "results", process the array. But problem is array_keys is not reaching into the "results"
php's foreach loop is what you need.
foreach($arr['keyId']['results'] as $key => $value) {
//$key contains key and $value contains values.
}
The array you want is $array['keyID']['results']. From there you access the values with $array['keyID']['results'][1], $array['keyID']['results'][2], $array['keyID']['results'][3]
To loop through it just do this:
foreach($array['keyId']['results'] as $key => $value) {
echo $key . ' ' . $value;
}
or
for ($i = 1; $i <= 3; i++)
{
echo $i . ' ' . $array['keyID']['results'][i];
}
foreach($array['keyId']['results'] as $k => $v) {
// use $k and $v
}
One way to navigate through the array is this.
//Assuming, your main array is $array
foreach($array as $value) { //iterate over each item
if(isset($value['results']) && count($value['results'])) {
// ^ check if results is present
//Now that we know results exists, lets use foreach loop again to get the values
foreach($value['result'] as $k => $v) {
//The boolean values are now accessible with $v
}
}
}

Categories