How should I make this array value that is in string form
Array
(
[0] => ["1","2"]
[1] => ["5"]
)
into int form
Array
(
[0] => 1
[1] => 2
[2] => 5
)
Is it complicated? Anyone can help?
you can use array_map to parse string to int and array_reduce with array_merge to join the arrays
$data = Array(["1","2"],["5"]);
$result = array_map('intval', array_reduce($data, 'array_merge', array()));
print_r($result);
Try this:
$array = [
["1", "2"],
["5"],
];
$newArray = [];
foreach ($array as $rowArr) {
foreach ($rowArr as $str) {
$newArray[] = intval($str);
}
}
var_dump($newArray);
This returns:
array (size=3)
0 => int 1
1 => int 2
2 => int 5
This works by iterating $array, then iterating $array's child elements ($rowArr) and adding each element to $newArray after running intval on it.
Use array_reduce (https://3v4l.org/H4eIV)
$a = Array
(
0=> ["1","2"],
1=> ["5"]
);
$r = array_reduce($a, 'array_merge', array());
var_export($r);
Result:
array (
0 => '1',
1 => '2',
2 => '5',
)
You only need to loop through the two layers of your array.
$input=[["1","2"],["5"]];
foreach($input as $a){
foreach($a as $v){
$result[]=+$v; // make integer
}
}
var_export($result);
Another way: create a closure that casts variables to ints and appends them to an array.
$appendInt = function($x) use (&$result) { $result[] = (int) $x; };
// reference to result array^ append to result^ ^cast to int
Apply it to every element of your multidimensional array with array_walk_recursive.
array_walk_recursive($your_array, $appendInt);
The flat array of ints will be in the $result variable.
Related
Here is an example array I want to split:
(1428,217,1428)
How do I split it in 2 array like this?
(1428,1428)
(217)
I have tried following way but it's only return 1428 array.
$counts = array_count_values($array);
$filtered = array_filter($array, function ($value) use ($counts) {
return $counts[$value] > 1;
});
One way to solve this for your example data is to sort the array and use array_shift to get the first element of the array and store that in an array.
$a = [1428,217,1428];
sort($a);
$b = [array_shift($a)];
print_r($a);
print_r($b);
Result
Array
(
[0] => 1428
[1] => 1428
)
Array
(
[0] => 217
)
You can try this.
$array = array(1428,217,1428);
$array1 = array_slice($array, 0, 2);
$array2 = array_slice($array, 2, 3);
print_r($array1);
print_r($array2);
And the output will like this:-
Array
(
[0] => 1428
[1] => 217
)
Array
(
[0] => 1428
)
In your case it will only return 1428 since array_count_values returns an array with values as keys and their frequency as array value therefore $counts will be equal to array('1428' => 2, '217' => 1);
If I understood your question well you should do something like this:
$array1 = [1428, 217, 1428];
$result = [];
foreach($array1 as $value){
$result[$value][] = $value;
}
This will not create an array for each different value but will create a new element for each unique value in $result. The final value of $result will be array('1428' => [1428, 1428], '217' => [217]) . Which can be easily manipulated as if they were 2 different arrays.
Let me know if this works for you, if not I will try to update my answer according to your specification.
I am using the Flot jQuery plugin to create a graph on how many visitors there have been per platform. I would like to create a 4th line with total visitors, calculated by previously retrieved data.
I need to combine several multi-dimensional Indexed arrays, but not simply merging them recursively. I.E:
$arr1 = [[2016/05/04,2],[2016/05/03,4],[2016/05/02,6]];
$arr2 = [[2016/05/04,1],[2016/05/03,3],[2016/05/02,2]];
$arr3 = [[2016/05/04,6],[2016/05/03,7],[2016/05/02,8]];
The output should be:
$arrTotal = [[2016/05/04,9],[2016/05/03,14],[2016/05/02,16]];
How do I accomplish this in a (fairly) simple way?
First of all, you cannot declare your dates the way you did:
$arr1 = [[2016/05/04,2],[2016/05/03,4],[2016/05/02,6]];
Because it's going to take 2016, divide it by 5 then divide it by 4. You need to put them into quotes.
$arr1 = [['2016/05/04',2],['2016/05/03',4],['2016/05/02',6]];
But to create an associative array, you should do it this way:
$arr1 = array('2016/05/04' => 2, '2016/05/03' => 4, '2016/05/02' => 6);
$arr2 = array('2016/05/04' => 1, '2016/05/03' => 3, '2016/05/02' => 2);
$arr3 = array('2016/05/04' => 6, '2016/05/03' => 7, '2016/05/02' => 8);
Now all you want to do, is loop through each array and sum them up.
$merge = array();
function mergeArray(Array &$merge, Array $array){
// Loop through each key and value
foreach($array as $key => $value)
// Make sure the value is numeric
if(is_numeric($value)){
if(!isset($merge[$key]))
$merge[$key] = $value;
else
$merge[$key] += $value;
}
}
mergeArray($merge, $arr1);
mergeArray($merge, $arr2);
mergeArray($merge, $arr3);
And now if you dump the $merge:
array(3) {
["2016/05/04"]=>
int(9)
["2016/05/03"]=>
int(14)
["2016/05/02"]=>
int(16)
}
Build a method that will sum the values by respecting the keys of existing values.
$arr1 = array('2016/05/04'=>2,'2016/05/03'=>4,'2016/05/02'=>6);
$arr2 = array('2016/05/04'=>1,'2016/05/03'=>3,'2016/05/02'=>2);
$arr3 = array('2016/05/04'=>2,'2016/05/03'=>7,'2016/05/02'=>8);
function array_sum(&$new_arr,$arr) {
foreach ($arr as $date_key => $num_value) {
// initialize date in new array with 0, if not done previously
if (! isset($new_arr[$date_key])) { $new_arr[$date_key] = 0; }
// add number for indexed element of array
$new_arr[$date_key] += $num_value;
}
}
$new_arr = array();
array_sum($new_array,$arr1);
array_sum($new_array,$arr2);
array_sum($new_array,$arr3);
You are trying to sum up every second value from each nested array relatively to their position in the parent array.There's a short and simple solution using array_map, array_sum and array_column functions:
$groupped = array_map(null, $arr1,$arr2,$arr3);
$result = array_map(function($v){
return [$v[0][0], array_sum(array_column($v, 1))];
}, $groupped);
print_r($result);
The output:
Array
(
[0] => Array
(
[0] => 2016/05/04
[1] => 9
)
[1] => Array
(
[0] => 2016/05/03
[1] => 14
)
[2] => Array
(
[0] => 2016/05/02
[1] => 16
)
)
I have an array like this:
<?php
$array = array( 0 => 'foo', 1 => 'bar', ..., x => 'foobar' );
?>
What is the fastest way to create a multidimensional array out of this, where every value is another level?
So I get:
array (size=1)
'foo' =>
array (size=1)
'bar' =>
...
array (size=1)
'x' =>
array (size=1)
0 => string 'foobar' (length=6)
<?php
$i = count($array)-1;
$lasta = array($array[$i]);
$i--;
while ($i>=0)
{
$a = array();
$a[$array[$i]] = $lasta;
$lasta = $a;
$i--;
}
?>
$a is the output.
What exactly are you trying to do? So many arrays of size 1 seems a bit silly.
you probably want to use foreach loop(s) with a key=>value pair
foreach ($array as $k=>$v) {
print "key: $k value: $v";
}
You could do something like this to achieve the array you asked for:
$newArray = array();
for ($i=count($array)-1; $i>=0; $i--) {
$newArray = array($newArray[$i]=>$newArray);
}
I'm confused about what you want to do with non-numeric keys (ie, x in your example). But in any case using array references will help
$array = array( 0 => 'foo', 1 => 'bar', x => 'foobar' );
$out = array();
$curr = &$out;
foreach ($array as $key => $value) {
$curr[$value] = array();
$curr = &$curr[$value];
}
print( "In: \n" );
print_r($array);
print( "Out : \n" );
print_r($out);
Prints out
In:
Array
(
[0] => foo
[1] => bar
[x] => foobar
)
Out :
Array
(
[foo] => Array
(
[bar] => Array
(
[foobar] => Array
(
)
)
)
)
You can use a recursive function so that you're not iterating through the array each step. Here's such a function I wrote.
function expand_arr($arr)
{
if (empty($arr))
return array();
return array(
array_shift($arr) => expand_arr($arr)
);
}
Your question is a little unclear since in your initial statement you're using the next value in the array as the next step down's key and then at the end of your example you're using the original key as the only key in the next step's key.
Which method is best practice to turn a multidimensional array
Array ( [0] => Array ( [id] => 11 ) [1] => Array ( [id] => 14 ) )
into a simple array? edit: "flattened" array (thanks arxanas for the right word)
Array ( [0] => 11 [1] => 14 )
I saw some examples but is there an easier way besides foreach loops, implode, or big functions? Surely there must a php function that handles this. Or not..?
$array = array();
$newArray = array();
foreach ( $array as $key => $val )
{
$temp = array_values($val);
$newArray[] = $temp[0];
}
See it here in action: http://viper-7.com/sWfSbD
Here you have it in function form:
function array_flatten ( $array )
{
$out = array();
foreach ( $array as $key => $val )
{
$temp = array_values($val);
$out[] = $temp[0];
}
return $out;
}
See it here in action: http://viper-7.com/psvYNO
You could use array_walk_recursive to flatten an array.
$ret = array();
array_walk_recursive($arr, function($var) use (&$ret) {
$ret[] = $var;
});
var_dump($ret);
If you have a multidimensional array that shouldn't be a multidimensional array (has the same keys and values) and it has multiple depths of dimension, you can just use recursion to loop through it and append each item to a new array. Just be sure not to get a headache with it :)
Here's an example. (It's probably not as "elegant" as xdazz", but it's an alternate without using "use" closure.) This is how the array might start out like:
Start
array (size=2)
0 =>
array (size=1)
'woeid' => string '56413072' (length=8)
1 =>
array (size=1)
'woeid' => string '56412936' (length=8)
Then you might want to have something like this:
Target
array (size=2)
0 => string '56413072' (length=8)
1 => string '56412936' (length=8)
You can use array_walk_recursive
Code
$woeid = array();
array_walk_recursive($result['results']['Result'], function ($item, $key, $woeid) {
if ($key == 'woeid') {
$woeid[] = $item;
}
}, &$woeid);
I have this foreach loop:
foreach($aMbs as $aMemb){
$ignoreArray = array(1,3);
if (!in_array($aMemb['ID'],$ignoreArray)){
$aMemberships[] = array($aMemb['ID'] => $aMemb['Name']);
}
}
This prints out the right fields but they are arrays inside arrays. I need the foreach loop to output a simple array like this one:
$aMemberships = array('1' => 'Standard', '2' => 'Silver');
What am I doing wrong?
You need to change your $aMemberships assignment
$aMemberships[] = $aMemb['Name'];
If you want an array
$aMemberships[$aMemb['ID']] = $aMemb['Name'];
if you want a map.
What you are doing is appending an array to an array.
Associative array in foreach statement:
foreach($nodeids as $field => $value) {
$field_data[$field]=$value;
}
Output:
Array(
$field => $value,
$field => $value
...
);
insertion in CodeIgniter:
$res=$this->db->insert($bundle_table,$field_data);
Instead of
$aMemberships[] = array($aMemb['ID'] => $aMemb['Name']);
Try
$aMemberships[$aMemb['ID']] = $aMemb['Name'];
Your existing code uses incremental key and uses the array as corresponding value.
To make make $aMemberships an associative array with key as $aMemb['ID'] and value being $aMemb['Name'] you need to change
$aMemberships[] = array($aMemb['ID'] => $aMemb['Name']);
in the foreach loop to:
$aMemberships[$aMemb['ID']] = $aMemb['Name']);
it prints an array of arrays because you are doing so in this line
$aMemberships[] = array($aMemb['ID'] => $aMemb['Name']);
where you [] after a variable your are indicating to assign the value in a new row of the array and you are inserting an other array into that row
so you can use the the examples the others haver already gave or you can use this method:
int array_push ( array &$array , mixed $var [, mixed $... ] )
here is an example that you can find in the api
<?php
$stack = array(0=>"orange",1=>"banana");
array_push($stack, 2=>"apple",3=>"raspberry");
print_r($stack);
?>
//prints
Array
(
[0] => orange
[1] => banana
[2] => apple
[3] => raspberry
)
http://php.net/manual/en/function.array-push.php
You get key and value of an associative array in foreach loop and create an associative with key and value pairs.
$aMemberships=array();//define array
foreach($aMbs as $key=>$value){
$ignoreArray = array(1,3);
if (!in_array($key,$ignoreArray)){
$aMemberships[$key] = $value;
}
}
It will give you an expected output:
array('1' => 'Standard', '2' => 'Silver');