I have an arrays like:
$array1=array(1,2,3,4),
$array2=array("test1","test2","test3","test4"),
$array3=array("2014","2015","2014","2015"),
$array4=array("201","101","203","104")
Now I want to create a new multidimensional array $array4 with values like:
[0]=>{"1","test1","2014","201"}
[1]=>{"2","test2","2015","101"}
[2]=>{"3","test3","2014","203"}
[3]=>{"4","test4","2015","104"}
The code you need is given as an example in the documentation page of function array_map():
$output = array_map(NULL, $array1, $array2, $array3, $array4);
That's all!
try this function:
$array1=array(1,2,3,4);
$array2=array("test1","test2","test3","test4");
$array3=array("2014","2015","2014","2015");
$array4=array("201","101","203","104");
print_r(convert($array1, $array2, $array3, $array4));
function convert() {
$newArr = [];
$arrays = func_get_args();
for ($i = 0; $i < count($arrays);$i++) {
for ($k = 0; $k < count($arrays[$i]); $k++) {
$newArr[$k][$i] = $arrays[$i][$k];
}
}
return $newArr;
}
You can make use of array_map to achieve the desired result:
$merge = function() {
return func_get_args();
};
$result = array_map($merge, $array1, $array2, $array3, $array4);
var_dump($result)
It looks like a job for function array_column():
// Combine all the input arrays into a single 2-dimensional array
// Pass the combined array to a function that will return the list
// of its columns
$output = transpose(array($array1, $array2, $array3, $array4));
function transpose(array $array)
{
// Store the result here
$result = array();
// Get each column, put it into the result
foreach (array_keys($array[0]) as $key) {
$result[$key] = array_column($array, $key);
}
return $result;
}
Another solution that works the same but uses function array_reduce() to walk the array:
function transpose(array $array)
{
return array_reduce(
array_keys($array[0]),
function (array $carry, $key) use ($array) {
$carry[$key] = array_column($array, $key);
return $carry;
},
array()
);
}
Related
$arr1 = array('foo'=>array('green'=>10, 'flowers'=>20), 'bar'=>20);
$arr2 = array('red'=>'roses', 'blue'=>'sky', foo=>array('flowers'=>15), 'bar'=>array('demo'=>'asdf'));
Desired result of the merge:
array('foo'=>array('green'=>10, 'flowers'=>15), 'bar'=>array('demo'=>'asdf'));
I have written a recursive function for this purpose, but I wonder if there is a more elegant way in PHP to achieve this.
This is my function:
function array_overwrite_recursive($arr1, $arr2) {
foreach($arr1 As $k=>$v) {
if(is_array($arr1[$k])) {
$arr1[$k] = array_overwrite_recursive($arr1[$k], $arr2[$k]);
} else {
if(isset($arr2[$k])) $arr1[$k]=$arr2[$k];
}
}
return $arr1;
}
$data = array
(
array("Ravi","Kuwait",350),
array("Sameer","UK",400),
array("Aditi","Switzerland",50),
array("Akshay","India",250),
array("rishi","Singapore",200),
array("Mukul","Ireland",100)
);
I want to put condition to the third row such that I can get entries of less than 300.
I suppose that you meant "the third element" in each nested array.Use array_filter function to get an array of elements, those third element's value is less than 300:
$result = array_filter($data, function($v) { return $v[2] < 300; });
print_r($result);
Try this code:
<?php
$data = array
(
array("Ravi","Kuwait",350),
array("Sameer","UK",400),
array("Aditi","Switzerland",50),
array("Akshay","India",250),
array("rishi","Singapore",200),
array("Mukul","Ireland",100)
);
$newArray = array();
foreach($data as $key => $value)
{
if($value[2] <= 100)
$newArray[] = $value;
}
print_r($newArray);
?>
You can achieve this using the PHP function array_filter() :
PHP
function limitArray($array) {
return ($array[2] <= 300);
}
print_r(array_filter($data, 'limitArray'));
evalIN
I have a :
$value = "val";
I also have an array :
$keys = ['key1', 'key2', 'key3'...]
The keys in that array are dynamically generated, and can go from 2 to 10 or more entries.
My goal is getting this :
$array['key1']['key2']['key3']... = $value;
How can I do that ?
Thanks
The easiest, and least messy way (ie not using references) would be to use a recursive function:
function addArrayLevels(array $keys, array $target)
{
if ($keys) {
$key = array_shift($keys);
$target[$key] = addArrayLevels($keys, []);
}
return $target;
}
//usage
$keys = range(1, 10);
$subArrays = addARrayLevels($keys, []);
It works as you can see here.
How it works is really quite simple:
if ($keys) {: if there's a key left to be added
$key = array_shift($keys); shift the first element from the array
$target[$key] = addArrayLevels($keys, []);: add the index to $target, and call the same function again with $keys (after having removed the first value). These recursive calls will go on until $keys is empty, and the function simply returns an empty array
The downsides:
Recursion can be tricky to get your head round at first, especially in complex functions, in code you didn't write, but document it well and you should be fine
The pro's:
It's more flexible (you can use $target as a sort of default/final assignment variable, with little effort (will add example below if I find the time)
No reference mess and risks to deal with
Example using adaptation of the function above to assign value at "lowest" level:
function addArrayLevels(array $keys, $value)
{
$return = [];
$key = array_shift($keys);
if ($keys) {
$return[$key] = addArrayLevels($keys, $value);
} else {
$return[$key] = $value;
}
return $return;
}
$keys = range(1, 10);
$subArrays = addARrayLevels($keys, 'innerValue');
var_dump($subArrays);
Demo
I don't think that there is built-in function for that but you can do that with simple foreach and references.
$newArray = [];
$keys = ['key1', 'key2', 'key3'];
$reference =& $newArray;
foreach ($keys as $key) {
$reference[$key] = [];
$reference =& $reference[$key];
}
unset($reference);
var_dump($newArray);
Why is 'the array pushed element' not echoed?
function dofoo1() {
$array = array("1aaa", "2bbbb", "3cccc");
$count = '######';
$array1 = array_push($array, $count);
return $array1;
}
$foo1 = dofoo1();
echo $foo1[3];
No need to assign array_push to a variable.
function dofoo1() {
$array = array("1aaa", "2bbbb", "3cccc");
$count = '######';
array_push($array, $count);
return $array;
}
$foo1 = dofoo1();
echo $foo1[3];
You can simply use array merge
function dofoo1() {
$array = array("1aaa", "2bbbb", "3cccc");
$count = '######';
return array_merge($array, array($count));
}
$foo1 = dofoo1();
echo $foo1[3];
array_push() Returns the new number of elements in the array.
So, You should return the array itself in which you have pushed,
Change,
return $array1;
to
return $array;
As described in the php docs array_push() alters the given array and returns only the number of elements.
Therefore you have to return $array instead of $array1.
If you just want to add one element, it is even better to avoid array_push() and use $array[] = $count; instead.
This usage is recommended in the docs of array_push().
So your code should look like this:
function dofoo1() {
$array = array("1aaa", "2bbbb", "3cccc");
$count = '######';
$array[] = $count;
return $array;
}
$foo1 = dofoo1();
echo $foo1[3];
I've written the below function, it takes in a 2 dimensional array and return the number of times a key occurs, BUT it feels like i may be reinventing the wheel here, is there an easy way?
function countKeys($array, $key)
{
$results = array();
foreach($array as $row)
{
if (array_key_exists($row[$key], $results))
{
$results[$row[$key]] += 1;
}
else
{
$results[$row[$key]] = 1;
}
}
return $results;
}
To count the keys in a two dimensional array with a search I would do this -
function countKeys($array,$search){
$key_count = array(); // new array
foreach($array as $record) {
$keys = array_keys($record);
foreach($keys as $key){
if($key == $search){ // check against the search term
array_push($key_count, $key); // add the key to the new array
}
}
}
return count($key_count); // just count the new array
}
echo countKeys($records, 'last_name');
EXAMPLE
array_keys()
count()
For a 2 dimensional array try:
$result = count(array_column($array, $key));
PHP >= 5.5.0 needed for array_column() or use the PHP Implementation of array_column()
Just use count() function like:
count($array);
see: http://php.net/manual/pt_BR/function.count.php
You can use this function to count arrays variable as well.
Hope it helps you.