How to convert two dimensional array to one dimensional array in php? - php

I am Having an mutidimensional array getting result like given below
Array
(
[0] => Array
(
[0] => 70
)
[1] => Array
(
[0] => 67
)
[2] => Array
(
[0] => 75
[1] => 73
[2] => 68
)
[3] => Array
(
[0] => 68
)
[4] => Array
(
[0] => 76
)
)
But I need to convert it to single array
And I want to convert in to single dimensional array as
Array
(
[0] => 70
[1] => 67
[2] => 75
[3] => 73
[4] => 68
[5] => 68
[6] => 76
)
How to convert it using php functions?
Or Is there any other way to do it?

You can try
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($data));
$l = iterator_to_array($it, false);
var_dump($l); // one Dimensional

Try with:
$input = array(/* your array*/);
$output = array();
foreach ( $input as $data ) {
$output = array_merge($output, $data);
}

You can use array_walk_recursive() for that coupled with a closure:
$res = array(); // initialize result
// apply closure to all items in $data
array_walk_recursive($data, function($item) use (&$res) {
// flatten the array
$res[] = $item;
});
print_r($res); // print one-dimensional array

This should do the trick
$final = array();
foreach ($outer as $inner) {
$final = array_merge($final, $inner);
}
var_dump($final);
Or you could use array_reduce() if you have PHP >= 5.3
$final = array_reduce($outer, function($_, $inner){
return $_ = array_merge((array)$_, $inner);
});
var_dump($final);

For a more generic function which can deal with multidimensional arrays, check this function,
function arrayFlattener($input = array(), &$output = array()) {
foreach($input as $value) {
if(is_array($value)) {
arrayFlattener($value, $output);
} else {
$output[] = $value;
}
}
}
You can find an example here.

By using this function you can convert any dimension array into a single dimention array.
$result = array();
$data = mearchIntoarray($result,$array);
function mearchIntoarray($result,$now)
{
global $result;
foreach($now as $key=>$val)
{
if(is_array($val))
{
mearchIntoarray($result,$val);
}
else
{
$result[] = $val;
}
}
return $result;
}
Where $array is your given array value.

Related

How to transfer one array to another array in php

I have a simple Two array
$ages[] = array("Peter"=>22, "Clark"=>32, "John"=>28);
$ages1[] = array("demo"=>22);
When I print this arrays it should be like following:
Array
(
[0] => Array
(
[Peter] => 22
[Clark] => 32
[John] => 28
)
)
Array
(
[0] => Array
(
[demo] => 22
)
)
But I want to create third array which will be show demo kye value into first array like following:
Array
(
[0] => Array
(
[Peter] => 22
[Clark] => 32
[John] => 28
[demo] => 22
)
)
Can we do two array into single array in PHP like Above
Not sure what are you trying to achieve here...little more context would be helpful. But this is how you can do this,
$ages[] = array("Peter"=>22, "Clark"=>32, "John"=>28);
$ages1[] = array("demo"=>22);
$result[] = array_merge($ages[0],$ages1[0]);
This would do the job.
<?php
$ages[] = array("Peter"=>22, "Clark"=>32, "John"=>28);
$ages1[] = array("demo"=>22);
$output = prepend_array($ages,$ages1);
print_r($output);
// Function to prepend arrays
function prepend_array()
{
$num_args = count(func_get_args());
$new_array = array();
foreach (func_get_args() as $params){
foreach($params as $out_key => $param)
{
foreach($param as $key => $value)
$new_array[$out_key][$key] = $value;
}
}
return $new_array;
}

Explode array's data and make new array

I have this array:
Array
(
[0] => Array
(
[0] => 1
[1] => a,b,c
)
[1] => Array
(
[0] => 5
[1] => d,e,f
)
)
I want the final array to be this:
Array
(
[0] => Array
(
[0] => 1
[1] => a
)
[1] => Array
(
[0] => 1
[1] => b
)
[2] => Array
(
[0] => 1
[1] => c
)
[3] => Array
(
[0] => 5
[1] => d
)
[4] => Array
(
[0] => 5
[1] => e
)
[5] => Array
(
[0] => 5
[1] => f
)
)
This is what I did:
<?php
$array = array(array(1,"a,b,c"),array(5,"d,e,f"));
$temp=array();
$count = 0;
foreach($array as $arr){
$rows = explode(",",$arr[1]);
foreach($rows as $row){
$temp[$count] = $arr;
$temp[$count][1] = $row;
$count++;
}
}
print_r($temp);
?>
This totally works but I was wondering if there was a better way to do this. This can be very slow when I have huge data.
Try like this way...
<?php
$array = array(array(1,"a,b,c"),array(5,"d,e,f"));
$temp=array();
$count = 0;
foreach($array as $arr){
$rows = explode(",",$arr[1]);
foreach($rows as $row){
$temp[$count][] = $arr[0];
$temp[$count][] = $row;
$count++;
}
}
/*print "<pre>";
print_r($temp);
print "<pre>";*/
?>
Here's a functional approach:
$result = array_merge(...array_map(function(array $a) {
return array_map(function($x) use ($a) {
return [$a[0], $x];
}, explode(",", $a[1]));
}, $array));
Try it online.
Or simply with two loops:
$result = [];
foreach ($array as $a) {
foreach (explode(",", $a[1]) as $x) {
$result[] = [$a[0], $x];
}
}
Try it online.
Timing these reveals that a simple loop construct is ~8 times faster.
functional: 4.06s user 0.08s system 99% cpu 4.160 total
loop: 0.53s user 0.05s system 102% cpu 0.561 total
If you need other way around,
$array = array(array(1, "a,b,c"), array(5, "d,e,f"));
$temp = [];
array_walk($array, function ($item, $key) use (&$temp) {
$second = explode(',', $item[1]);
foreach ($second as $v) {
$temp[] = [$item[0], $v];
}
});
print_r($temp);
array_walk — Apply a user supplied function to every member of an array
Here is working demo.

create new array from existing array

I have multiple arrays like this:
array (
[floorBuildingName] => Array
(
[0] => Lt.1
[1] => Lt.2
)
[roomFloorName] => Array
(
[0] => Single
[1] => Medium1
[2] => MaXI
)
)
I would like to merge the two arrays into a single array.
For example:
array (
[0] => array(
[0] =>Lt.1,
[1] =>Single
),
[1] => array(
[0] =>Lt.2,
[1] =>Medium1
),
[2] => array(
[0] =>Lt.2,
[1] =>MaXI
)
)
How can I achieve this?
First, you have to determine the maximum array length. Then, create a new array and finally, put the elements at the given index into the new array. If the index is out of bounds, then use the last element.
var $maxNumber = 0;
foreach ($myArray as $array) {
$maxNumber = max($maxNumber, count($array));
}
$result = array();
for ($index = 0; $index < $maxNumber; $index++) {
$result[] = array();
foreach($myArray as $array) {
if (count($array) < $maxNumber) {
$result[$index][] = $array(count($array) - 1);
} else {
$result[$index][] = $array[$index];
}
}
}
Assuming that you want to pad out uneven arrays with the last value in the array:
$data = ['floorBuildingName' => [..], ..];
// find the longest inner array
$max = max(array_map('count', $data));
// pad all arrays to the longest length
$data = array_map(function ($array) use ($max) {
return array_pad($array, $max, end($array));
}, $data);
// merge them
$merged = array_map(null, $data['floorBuildingName'], $data['roomFloorName']);
You can do this using array_map very Easily:
Try this code:
$arr1 = array(1, 2);
$arr2 = array('one', 'two', 'three', 'four');
while(count($arr1) != count($arr2)) {
//If Array1 is Shorter then Array2
if (count($arr1)<count($arr2)) {
$arr1[] = $arr1[count($arr1) - 1];
}
//If Array2 is Shorter then Array1
if (count($arr1) > count($arr2)) {
$arr2[] = $arr2[count($arr2) - 1];
}
}
//Now merge arrays
$newarray = (array_map(null, $arr1, $arr2));
print_r($newarray);
Will Output:
Array
(
[0] => Array
(
[0] => 1
[1] => one
)
[1] => Array
(
[0] => 2
[1] => two
)
[2] => Array
(
[0] => 2
[1] => three
)
[3] => Array
(
[0] => 2
[1] => four
)
)
there's the solution for different number of arguments:
$floorBuildingName = array(
'Lt.1',
'Lt.2'
);
$roomFloorName = array(
'Single', 'Medium1', 'MaXI'
);
class ValueArrayIterator extends ArrayIterator
{
protected $arrays;
protected $latestValues = [];
public function __construct(array $mainArray) {
parent::__construct($mainArray);
$this->arrays = func_get_args();
}
public function current()
{
$returnValue = [];
foreach ($this->arrays as $arrayKey => $array) {
if (isset($array[$this->key()])) {
$this->latestValues[$arrayKey] = $array[$this->key()];
}
$returnValue[] = $this->latestValues[$arrayKey];
}
return $returnValue;
}
}
$iterator = new ValueArrayIterator($roomFloorName, $floorBuildingName);
$newArray = iterator_to_array($iterator);

manipulate a 2D array in PHP

I have a 2 Dimentional array in php as follow :
Array
(
[0] => Array
(
[0] => 10
[1] =>
)
[1] => Array
(
[0] => 67
[1] =>
)
[2] => Array
(
[0] => 67
[1] => 50
)
)
I want to manipulate it as follow:
Array
(
[0] => Array
(
[0] => 10
[1] => 67
[2] => 67
)
[1] => Array
(
[0] =>
[1] =>
[2] => 50
)
)
Means I want to take first elements of all inner arrays in one array and 2nd element in another array.
How can I manipulate this. Plz help
You can array_map() instead of loop. Example:
$newArr[] = array_map(function($v){return $v[0];},$arr);
$newArr[] = array_map(function($v){return $v[1];},$arr);
Or can use array_column() if your PHP 5.5+
$newArr[] = array_column($arr, 0);
$newArr[] = array_column($arr, 1);
print '<pre>';
print_r($newArr);
print '</pre>';
Just run the following script:
$array1 = array();
for ($i = 0; $i < count($array1); $i++) {
for ($j = 0; $j < count($array1[$i]); $j++) {
$array2[$j][$i] = $array1[$i][$j];
}
}
Here's a general solution that works regardless of how many items you have in the array and the sub-arrays:
// Set up an array for testing
$my_array = array( array(10, null), array(67, null), array(67, 50));
/**
* Our magic function; takes an array and produces a consolidated array like you requested
* #param array $data The unprocessed data
* #return array
*/
function consolidate_sub_arrays($data)
{
/**
* The return array
* #var array $return_array
*/
$return_array = array();
// Loop over the existing array
foreach ($data as $outer) {
// Loop over the inner arrays (sub-arrays)
foreach($outer as $key => $val) {
// Set up a new sub-array in the return array, if it doesn't exist
if (!array_key_exists($key, $return_array)) {
$return_array[$key] = array();
}
// Add the value to the appropriate sub-array of the return array
$return_array[$key][] = $val;
}
}
// Done!
return $return_array;
}
// Just to verify it works; delete this in production
print_r(consolidate_sub_arrays($my_array));
You need to loop over the initial array and create a new array in the format you want it.
$new_array = array();
foreach ($input_array as $in ) {
$new_array[0][] = $in[0];
$new_array[1][] = $in[1];
}
print_r($new_array);

Looping an array through a second array

Looking to loop through an array of URLs and inject each keyword from a second array into each URL but can't get to grips with the understanding of arrays. Eg:
$key = array("Keyword+1", "Keyword+2", "Keyword+3"),
$url =array("google.co.uk/#hl=en&q=", "bing.com/search?q=","uk.search.yahoo.com/search?vc=&p="),
I'd like the above to output:
google.co.uk/#hl=en&q=Keyword+1
google.co.uk/#hl=en&q=Keyword+2
google.co.uk/#hl=en&q=Keyword+3
bing.com/search?q=Keyword+1
bing.com/search?q=Keyword+2
bing.com/search?q=Keyword+3
uk.search.yahoo.com/search?vc=&p=Keyword+1
uk.search.yahoo.com/search?vc=&p=Keyword+2
uk.search.yahoo.com/search?vc=&p=Keyword+3
Is there an efficient way to achieve this? :)
foreach($url as $currenturl)
{
foreach($key as $currentkey)
{
echo $currenturl . $currentkey . '\n';
}
}
try this
Here is how you can do that:
$keys = array("Keyword+1", "Keyword+2", "Keyword+3");
$urls =array("google.co.uk/#hl=en&q=", "bing.com/search?q=","uk.search.yahoo.com/search?vc=&p=");
$my_array = array();
foreach($urls as $url)
{
foreach($keys as $key)
{
$my_array[] = $url . $key;
}
}
print_r($my_array);
Result:
Array
(
[0] => google.co.uk/#hl=en&q=Keyword+1
[1] => google.co.uk/#hl=en&q=Keyword+2
[2] => google.co.uk/#hl=en&q=Keyword+3
[3] => bing.com/search?q=Keyword+1
[4] => bing.com/search?q=Keyword+2
[5] => bing.com/search?q=Keyword+3
[6] => uk.search.yahoo.com/search?vc=&p=Keyword+1
[7] => uk.search.yahoo.com/search?vc=&p=Keyword+2
[8] => uk.search.yahoo.com/search?vc=&p=Keyword+3
)
You first want to loop over the $url array, then for each item in the $url array, you also want to loop over all the keys in the $key array and append them to the item you picked from $url,
foreach ($url as $u)
{
foreach ($key as $k)
{
echo $u.$k."\n";
}
}
What you're describing is a generalization of the outer product.
It would be more interesting to define a higher order function for this:
/**
* A generalization of the outer product, forming all the possible
* combinations of the elements of the two arrays and feeding them
* to $f.
* The keys are disregarded
**/
function array_outer($f, array $array1, array $array2) {
$res = array();
foreach ($array1 as $e1) {
$cur = array();
foreach ($array2 as $e2) {
$cur[] = $f($e1, $e2);
}
$res[] = $cur;
}
return $res;
}
$f = function ($a,$b) { return $a.$b; };
print_r(array_outer($f, array("a","b","c"), array("1", "2", "3")));
gives:
Array
(
[0] => Array
(
[0] => a1
[1] => a2
[2] => a3
)
[1] => Array
(
[0] => b1
[1] => b2
[2] => b3
)
[2] => Array
(
[0] => c1
[1] => c2
[2] => c3
)
)
See Mathematica's Outer.

Categories