string values of bidimensional array into int values - php

I have an bidimensional array like this (all the values are strings)
Array (
[0]=>Array([ENE] => 22 [FEB] => 24)
[1]=>Array( [MAR] => 16 [ABR] => 33 )
[2]=>Array([MAY] => 18 [JUN] => 19)
)
But I need to make that string values into integer.
I found the following answer that works just with simple arrays.
If you have array like:
$runners = ["1","2","3","4"];
And if you want to covert them into integers and keep within array, following should do the job:
$newArray = array_map( create_function('$value', 'return (int)$value;'),
$runners);
Do you have any idea about how to do the same but with bidimensional arrays?

You will have to loop the array and convert every value to in with like this
for($i=0;$i<count($array);$i++){
$elements = $array[$i];
$values = array_map(function($arrayElement) { return (int)$arrayElement; },$elements);
$array[$i] = $values;
}

$runners = array(
array('ENE' => "22", 'FEB' => "24"),
array('MAR' => "16", 'ABR' => "33"),
array('MAY' => "18", 'JUN' => "19")
);
$func = function($subarray){
$tempArray = array();
foreach($subarray as $key => $val)
{
$tempArray[$key] = (int)$val;
}
return $tempArray;
}
$new_array = array_map($func, $runners);
This should work fine.

Related

How to convert multi-dimensional array into single array using PHP?

After implementing database queries, I am getting the multi-dimensional array below.
Two Dimensional Array
Array
(
[0] => Array
(
[t1] => test1
)
[1] => Array
(
[t2] => test2
)
[2] => Array
(
[t3] => test3
)
[3] => Array
(
[t4] => test4
)
[4] => Array
(
[t5] => test5
)
)
but I want to convert it to a single dimensional array, like the format below:
One Dimensional Array
Array (
t1 => test1
t2 => test2
t3 => test3
t4 => test4
t5 => test5
)
How can I do this?
I think you can use array_reduce() function.
For example:
$multi= array(0 => array('t1' => 'test1'),1 => array('t2' => 'test2'),2 => array('t3' => 'test3'),3 => array('t4' => 'test4'));
$single= array_reduce($multi, 'array_merge', array());
print_r($single); //Outputs the reduced aray
You can use as follows :
$newArray = array();
foreach($arrayData as $key => $value) {
foreach($value as $key2 => $value2) {
$newArray[$key2] = $value2;
}
}
Where $arrayData is your DB data array and $newArray will be the result.
Assuming that source array is array of arrays and it has no the same keys:
<?php
$src = [
['t1'=>'test1'],
['t2'=>'test2'],
['t3'=>'test3'],
['t4'=>'test4'],
['t5'=>'test5'],
];
$result = call_user_func_array('array_merge', $src);
result via var_dump():
array(5) {
["t1"]=>
string(5) "test1"
["t2"]=>
string(5) "test2"
["t3"]=>
string(5) "test3"
["t4"]=>
string(5) "test4"
["t5"]=>
string(5) "test5"
}
You can use array_reduce() to change values of array. In callback get key of item using key() and select first item using reset().
$newArr = array_reduce($oldArr, function($carry, $item){
$carry[key($item)] = reset($item);
return $carry;
});
Check result in demo
Try this function,
function custom_function($input_array)
{
$output_array = array();
for ($i = 0; $i < count($input_array); $i++) {
for ($j = 0; $j < count($input_array[$i]); $j++) {
$output_array[key($input_array[$i])] = $input_array[$i][key($input_array[$i])];
}
}
return $output_array;
}
$arr = custom_function($arr);
print_r($arr);
Give it a try, it will work.
You can use this
<?php
$temp = array(array('t1' => 'test1'), array('t2' => 'test2'), array('t3' => 'test3'), array('t4' => 'test4'), array('t5' => 'test5'));
$result_array = array();
foreach ($temp as $val) {
foreach ($val as $key => $inner_val) {
$result_array[$key] = $inner_val;
}
}
print_r($result_array);
?>
// Multidimensional array
$arrdata = Array(
'0' => Array(
't1' => 'test1'
) ,
'1' => Array(
't2' => 'test2'
) ,
'2' => Array(
't3' => 'test3'
)
);
// Convert to a single array
$data = array();
foreach($arrdata as $key => $value) {
foreach($value as $key1 => $value1) {
$data[$key1] = $value1;
}
}
echo $data;
Try array map function.
$singleDimensionArray = array_map('current',$multiDimensionArray);
You can use this if you don't care about keeping the correct array keys
function flattenA(array $array) {
$return = array();
array_walk_recursive($array, function($a) use (&$return) { $return[] = $a; });
return $return;
}
print_r(flattenA($arr));
// Output
Array
(
[0] => test1
[1] => test2
[2] => test3
[3] => test4
[4] => test5
)
Otherwise
function flattenB(array $array) {
$return = array();
array_walk_recursive($array, function($v,$k) use (&$return) { $return[$k] = $v; });
return $return;
}
print_r(flattenB($arr));
// Output
Array
(
[t1] => test1
[t2] => test2
[t3] => test3
[t4] => test4
[t5] => test5
)
Check both on Sandbox
From answer on similar question
For your specific case, I would use array_reduce where I set the initial value with an empty array
array_reduce($arr, function($last, $row) {
return $last + $row;
}, array());
AFTER PHP 7.4
array_reduce($arr, fn ($last, $row) => $last + $row, []);
Result :
[
't1' => 'test1',
't2' => 'test2',
't3' => 'test3',
't4' => 'test4',
't5' => 'test5'
]
Hey #Karan Adhikari Simple like below one:
<?php
$arr1 = array(array("t1" => "test1"), array("t2" => "test2"), array("t3" => "test3"), array("t4" => "test4"), array("t5" => "test5"));
echo "<pre>";
print_r($arr1);//before
$arr2 = array();
foreach($arr1 as $val){
$arr2 = array_merge($arr2, $val);
}
echo "<pre>";
print_r($arr2); // after you get your answer
Please try this function:
function array_merging($multi_array) {
if (is_array($multi_array)) {
$new_arr = array();
foreach ($multi_array as $key => $value) {
if (is_array($value)) {
$new_arr = array_merge($new_arr, array_merging($value));
}
else {
$new_arr[$key] = $value;
}
}
return $new_arr;
}
else {
return false;
}
}
Use this function:
$your_multi_arr = array(array(array('t1'=>'test1'),array('t2'=>'test2'),array('t3'=>'test3'),array('t4'=>'test4')));
$arr1 = array_merging($your_multi_arr);
echo "<pre>";
print_r($arr1);
Hope, this may be useful for you.
You can try traversing the array using PHP while list and each. I took sample code from PHP website the second example you can check it here
$arr = [['t1' => 'test1'],['t2' => 'test2'],['t3' => 'test3'],['t4' => 'test4'],['t5' => 'test5']];
$output = [];
while (list($key, $val) = each($arr)) {
while (list($k, $v) = each($val)) {
$output[$k] = $v;
}
}
print_r($output);
Output created is
Array
(
[t1] => test1
[t2] => test2
[t3] => test3
[t4] => test4
[t5] => test5
)
You can test it on your own in this Sandbox example.
This will do the trick
$array = array_column($array, 't1');
Note: This function array_column introduced in PHP 5.5 so it won't work in earlier versions.
traverse the array and save the key value, Live Demo here.
<?php
$array = array(array('t1' => 'test1'), array('t2' => 'test2'), array('t3' => 'test3'), array('t4' => 'test4'), array('t5' => 'test5'));
$result = [];
array_walk($array, function($value) use(&$result){
foreach($value as $k => $v)
{
$result[$k] = $v;
}
});
var_dump($result);
`$result = "Query"; $key_value = array();`
foreach ($result as $key => $value) {
$key_value[$key['']] = $value[''];
}
//for checking //echo "<pre>" ; print_r($key_value) ; exit;
return $key_value;
pls fill $key['name given in sql query for field'] and $value['name given in sql query for field'] (both are same)
this works for me
$result = [];
foreach($excelEmails as $arr)
{
foreach ($arr as $item){
$result = array_merge($result , $item);
}
}
dd($result);
i would recomment my way to convert all double-dimensional array to single-dimensional array.
<?php
$single_Array = array();
//example array
$array = array(
array('t1' => 'test1'),
array('t2' => 'test2'),
array('t3' => 'test3'),
array('t4' => 'test4'),
array('t5' => 'test5'));
$size = sizeof($array);
//loop to fill the new single-dimensional array
for($count = 0; $count<sizeof($array);$count++)
{
//take the key of multi-dim array
$second_cell = key($array[$count]);
//set the value into the new array
$single_array[$count] = $array[$count][$second_cell];
}
//see the results
var_dump($single_array);
?>
with this script we can take keys and values to create new single-dimensional array.I hope that i was helpfull to you.
you can see the example here: Array Convert Demo

Compare two arrays and return value

I have two arrays:
Array
(
[1] = 1575255
[2] = 1575258
)
Array
(
[Aantal kleuren opdruk] = Array
(
[1575252] = 1 kleur
[1575253] = 2 kleuren
[1575254] = 3 kleuren
[1575255] = 4 kleuren
)
[Opdrukpositie] = Array
(
[1575256] = Borst
[1575258] = Borst en rug
[1575257] = Rug
)
)
How can I compare the value of array 2 with the value of array 1 in their current order?
using array_column :
$arr = [];
foreach ($arr1 as $key => $value) {
$arr[] = array_column($arr2 ,$value);
}
print_r($arr);
assuming that the first array is $arr1 and the second is $arr2
EDIT
the one line solution using array_column and array_map
$arr = array_map(function($value) use ($arr2) {return array_column($arr2, $value);} ,$arr1);
print_r($arr);
OK so the first array has this. Take it as $a:
$a = ["1575255", "1575258"];
$second = ["Aantal kleuren opdruk" => [
"1575252" => "1 kleur",
"1575253" => "2 kleuren",
"1575254" => "3 kleuren",
"1575255" => "4 kleuren"
],
"Opdrukpositie" => [
"1575256" => "Borst",
"1575258" => "Borst en rug",
"1575257" => "Rug"
]
];
foreach($second as $val){
foreach($val as $key => $v){
if(in_array($key, $a)){
echo $v."<br>";
}
}
}

Converting multidimensional array's values into a key value pair in a one-dimensional array while taking out a prefix out of one of the values?

I have an array in the following format:
Array (
[0] => Array
(
[option_id] => 10820
[option_name] => PREFIX_FIRST_OPT_KEY
[option_value] => FIRST_OPT_VALUE
[autoload] => yes
)
[1] => Array
(
[option_id] => 10821
[option_name] => PREFIX_SECOND_OPT_KEY
[option_value] => SECOND_OPT_VALUE
[autoload] => yes
)
[2] => Array
(
[option_id] => 10824
[option_name] => PREFIX_THIRD_OPT_KEY
[option_value] => SECOND_OPT_VALUE
[autoload] => yes
)
)
What is the appropriate function to use to get a one dimensional associative array with the following structure?
Array (
[FIRST_OPT_KEY] => FIRST_OPT_VALUE
[SECOND_OPT_KEY] => SECOND_OPT_VALUE
[THIRD_OPT_KEY] => THIRD_OPT_VALUE
)
I only want to keep the indicated values as key value pairs in the new array and ignore the rest - PREFIX_ is fixed length.
What I am doing right now:
foreach ( $the_original_array as $key => $value ) {
$new_key = substr($the_original_array[$key]['option_name'], 7);
$option_value = $the_original_array[$key]['option_value'];
$new_array[$new_key] = $option_value;
}
but I feel there ought to be a cleaner/more efficient way of accomplishing this
If you have PHP >= 5.5:
To extract values:
$result = array_column($array, 'option_value', 'option_name');
Then to remove prefix:
$result = array_combine(
array_map(
function($k){
return str_replace('PREFIX_', '', $k);
},
array_keys($result)
), $result
);
A way of simulating array_column() if you aren't running PHP 5.5+
$newArray = array_combine(
array_map(
function($value) {
return substr($value['option_name'], 7);
},
$the_original_array
),
array_map(
function($value) {
return $value['option_value'];
},
$the_original_array
)
);
The accepted answer is valid, but it causes the data to be iterated over multiple times. Assuming PHP < 5.5.0, using array_reduce will loop over the data only once, and return the same result:
$iterator = function($result, $record) {
$key = substr($record['option_name'], 7);
$result[$key] = $record['option_value'];
return $result;
};
$newArray = array_reduce($original, $iterator, array());
I would use array_column but for PHP < 5.5.0 what you have is about the best you can do, but you can use the $value that is generated by the foreach:
foreach ( $the_original_array as $value ) {
$new_key = substr($value['option_name'], 7);
$option_value = $value['option_value'];
$new_array[$new_key] = $option_value;
}
I think than foreach is good like:
$new = array();
foreach ($original_array as $item) {
$index = str_replace('PREFIX_', '', $item['option_name']);
$new[$index] = $item['option_value'];
}

Cast all digital values in array as integer-type, otherwise leave non-digital values as strings

Given an array, how do I convert array starting at key [1] from type string to type int?
Array
(
[0] => "id"
[1] => "6086220176"
[2] => "6542925762"
[3] => "6623113406"
[4] => "6702782948"
)
I've checked out related question how to convert array values from string to int? already, but I would like to skip the first key "id" int he conversion, and not all keys in array!
array_walk($array, function (&$value) {
if (ctype_digit($value)) {
$value = (int) $value;
}
});
var_export($array);
Output:
array (
0 => 'id',
1 => 6086220176,
2 => 6542925762,
3 => 6623113406,
4 => 6702782948,
)
$arr = array_merge(array($arr[0]),array_map('intval', array_slice($arr, 1)));
Output:
array(5) {
[0]=>
string(2) "id"
[1]=>
int(2147483647)
[2]=>
int(2147483647)
[3]=>
int(2147483647)
[4]=>
int(2147483647)
}
Demo.
$array = array($array[0]) + array_map('intval', $array);
(if you want to avoid a foreach loop)
php is loosely typed, you don't need to type cast it. It will do it for you. But if you want to explicitly do this, you can do like this:
$c = count($array)-1;
for ($n=1;$n<$c;$n++) {
$array[$n] = (int) $array[$n];
}
foreach($array as $key => $val){
if($key !== 0){
$array[$key] = (int) $val;
}
}
or
foreach($array as $key => $val){
if(is_numeric($val)){
$array[$key] = (int) $val;
}
}
If all you values are int :
<?php
$arr = array(
[0] => "id"
[1] => "6086220176"
[2] => "6542925762"
[3] => "6623113406"
[4] => "6702782948"
);
$arr = array_map(function($var) {
// Your 'id' is not an int and will not be converted.
return is_numeric($var) ? (int)$var : $var;
}, $arr);
foreach($array as $k => $v){
if($k == 0) continue;
$array[$k] = is_int($v) ? intval($v) : $v; // if it's not convertible to int it keeps the value
}
or if you have non-numeric indexes
$skipped = false;
foreach($array as $k => $v){
if($skipped === false){
$skipped = true;
continue;
}
$array[$k] = is_int($v) ? intval($v) : $v;
}
Another technique not yet mentioned on this page is to encode the array as a json string with the JSON_NUMERIC_CHECK flag so that numeric values are appropriately cast as integers or floats. Then decode the generated string back to an array.
This approach does not require the developer to know in advance the key/index of the value nor require a conditional check on each value to see if the value is numeric. In simple terms, it is highly portable as a general-use strategy.
This technique conveniently accommodates arrays with more than one level.
Code: (Demo)
$array = [
"id",
"6086220176",
"6542925762",
"6623113406",
"6702782948",
['333', [['444']]]
];
var_export(
json_decode(
json_encode(
$array,
JSON_NUMERIC_CHECK
),
true
)
);
Output:
array (
0 => 'id',
1 => 6086220176,
2 => 6542925762,
3 => 6623113406,
4 => 6702782948,
5 =>
array (
0 => 333,
1 =>
array (
0 =>
array (
0 => 444,
),
),
),
)
It's not clever to do this but this could probably works:
$narray = array();
foreach($array as $k => $v){
$narray[$k+1] = $v;
}
$array = $narray;
$array is your array you want to start with 1.

PHP Adding multiple associative arrays to new array based on key

I have a few associative arrays that I need to merge together based on there key.
so:
array1:
[person1] => tony
[person2] => sandra
array2:
[person1] => london
[person2] => paris
needs to be :
array 3
[person1] => tony , london
[person2] => sandra , paris
The issue I'm having though is that the key could be any value , so it could be 'person1' or it could be 'hairyOtter' and the array is of varaible size.
Assuming, that every is not multi-dimensional
$merged = array_merge_recursive($array1, $array2);
foreach ($merged as &$entry) {
if (is_array($entry)) {
$entry = implode(', ', $entry);
}
}
The idea is, that array_merge_recursive() creates a new array, if it find two values with the same key. Everything else stays untouched.
I'm sure there are more efficient ways to accomplish this, but for now, this works:
<?php
function combine( $keys, $first, $second ) {
$args = func_get_args( );
$keys = array_shift( $args );
$arrays = $args;
$result = array( );
foreach( $keys as $key ) {
foreach( $arrays as $array ) {
if( isset( $array[$key] ) ) {
$result[$key][] = $array[$key];
}
}
}
return $result;
}
$first = array(
'person1' => 'tony',
'person2' => 'sandra'
);
$second = array(
'person1' => 'london',
'person2' => 'paris'
);
/**
* To make sure you get *every* key out of both arrays.
*/
$keys = array_unique( array_merge( array_keys( $first ), array_keys( $second ) ) );
$combined = combine( $keys, $first, $second );
var_dump( $combined );
Two loops should do it. Iterate over each of array1 and array2, initialising array3's keys as you go to an array, and pushing into that array. Here's the first loop
$array3 = array();
foreach (array_keys($array1) as $key) {
if(!array_key_exists($key, $array3)) {
$array3[$key] = array();
}
array_push($array3[$key], $array1[$key]);
}
$array1 = array('a' => 1, 'b' => 2);
$array2 = array('a' => 3, 'b' => 4, 'c' => 5);
foreach ($array1 as $k => $v) {
$tArray[$k][] = $v;
}
foreach ($array2 as $k => $v) {
$tArray[$k][] = $v;
}
foreach ($tArray as $k => $v) {
$tArray[$k] = implode(',',$tArray[$k]);
}
I would create a multi-dimensional array instead, unless there is a specific reason you can't use one. This way, you would have an array that looks like:
Array
(
[Person1] => Array
(
[Name] => Tony
[City] => London
)
[Person2] => Array
(
[Name] => Sandra
[City] => Paris
)
)

Categories