Related
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
I have an array that looks something like this:
Array (
[0] => Array ( [country_percentage] => 5 %North America )
[1] => Array ( [country_percentage] => 0 %Latin America )
)
I want only numeric values from above array. I want my final array like this
Array (
[0] => Array ( [country_percentage] => 5)
[1] => Array ( [country_percentage] => 0)
)
How I achieve this using PHP?? Thanks in advance...
When the number is in first position you can int cast it like so:
$newArray = [];
foreach($array => $value) {
$newArray[] = (int)$value;
}
I guess you can loop the 2 dimensional array and use a preg_replace, i.e.:
for($i=0; $i < count($arrays); $i++){
$arrays[$i]['country_percentage'] = preg_replace( '/[^\d]/', '', $arrays[$i]['country_percentage'] );
}
Ideone Demo
Update Based on your comment:
for($i=0; $i < count($arrays); $i++){
if( preg_match( '/North America/', $arrays[$i]['country_percentage'] )){
echo preg_replace( '/[^\d]/', '', $arrays[$i]['country_percentage'] );
}
}
Try this:
$arr = array(array('country_percentage' => '5 %North America'),array("country_percentage"=>"0 %Latin America"));
$result = array();
foreach($arr as $array) {
$int = filter_var($array['country_percentage'], FILTER_SANITIZE_NUMBER_INT);
$result[] = array('country_percentage' => $int);
}
Try this one:-
$arr =[['country_percentage' => '5 %North America'],
['country_percentage' => '0 %Latin America']];
$res = [];
foreach ($arr as $key => $val) {
$res[]['country_percentage'] = (int)$val['country_percentage'];
}
echo '<pre>'; print_r($res);
output:-
Array
(
[0] => Array
(
[country_percentage] => 5
)
[1] => Array
(
[country_percentage] => 0
)
)
You can use array_walk_recursive to do away with the loop,
passing the first parameter of the callback as a reference to modify the initial array value.
Then just apply either filter_var or intval as already mentioned the other answers.
$array = [
["country_percentage" => "5 %North America"],
["country_percentage" => "0 %Latin America"]
];
array_walk_recursive($array, function(&$value,$key){
$value = filter_var($value,FILTER_SANITIZE_NUMBER_INT);
// or
$value = intval($value);
});
print_r($array);
Will output
Array
(
[0] => Array
(
[country_percentage] => 5
)
[1] => Array
(
[country_percentage] => 0
)
)
You could get all nemeric values by looping through the array. However I don't think this is the most efficient and good looking answer, I'll post it anyways.
// Array to hold just the numbers
$newArray = array();
// Loop through array
foreach ($array as $key => $value) {
// Check if the value is numeric
if (is_numeric($value)) {
$newArray[$key] = $value;
}
}
I missunderstood your question.
$newArray = array();
foreach ($array as $key => $value) {
foreach ($value as $subkey => $subvalue) {
$subvalue = trim(current(explode('%', $subvalue)));
$newArray[$key] = array($subkey => $subvalue);
}
}
If you want all but numeric values :
$array[] = array("country_percentage"=>"5 %North America");
$array[] = array("country_percentage"=>"3 %Latin America");
$newArray = [];
foreach ($array as $arr){
foreach($arr as $key1=>$arr1) {
$newArray[][$key1] = intval($arr1);
}
}
echo "<pre>";
print_R($newArray);
This is kind of a ghetto method to doing it cause I love using not as many pre made functions as possible. But this should work for you :D
$array = array('jack', 2, 5, 'gday!');
$new = array();
foreach ($array as $item) {
// IF Is numeric (each item from the array) will insert into new array called $new.
if (is_numeric($item)) { array_push($new, $item); }
}
I want to delete an index from array and insert it into in new array. I want two things which i tried to explain one is
Array
(
[index1] => Deleted
[index4] => Inserted
)
Array
(
[index3] => test
[index4] => Inserted
)
Array
(
[index2] => numbers
[index3] => test
[index4] => Inserted
)
Array
(
[index1] => Deleted
)
now i want if arraysize is 1
foreach($array as $arrays){
array_push($array1,($arrays[0]));
unset ($arrays[0]);
}
i want to remove
Array
(
[index1] => Deleted
)
from $array and $array to be
[index1] => Deleted
second is if $array is
Array
(
[index2_123] => numbers
[index3_level] => test
[index4_test] => Inserted
)
i want a new array with $array1 as
Array
(
[index3_level] => test
)
and $array1 is modified to
Array
(
[index2_123] => numbers
[index4_test] => Inserted
)
Try this way,
$arr = Array
(
'index1' => 'Deleted',
'index2' => 'numbers',
'index3' => 'test',
'index4' => 'Inserted'
);
$arr1 = $arr2 = array();
$i = 0;
foreach($arr as $key => $value){
if($i%2 == 0){
$arr1[$key] = $value;
}else{
$arr2[$key] = $value;
}
$i++;
}
Output
$arr1
Array
(
[index1] => Deleted
[index3] => test
)
$arr2
Array
(
[index2] => numbers
[index4] => Inserted
)
And if you don't need that value then you can use it as
$i = 0;
foreach($arr as $key => $value){
if($i%2 == 0){
$arr[$key] = $value;
}else{
unset($arr[$key]);
}
$i++;
}
print_r($arr);
Output:
Array
(
[index1] => Deleted
[index3] => test
)
Loop through them and generate the array -
$new = array();
foreach($yourarray as $key => $val) {
$index = str_replace('index', '', $key); // get the key index
if($index % 2 != 0) { // check for odd or even
$new[$key] = $val; // set the new array
unset($yourarray[$key]); // delete from the main array
}
}
Update
For any index use a counter
$i = 0;
$new = array();
foreach($yourarray as $key => $val) {
if($i % 2 != 0) { // check for odd or even
$new[$key] = $val; // set the new array
unset($yourarray[$key]); // delete from the main array
}
$i++;
}
You can use a combination of array_flip and array_diff_key to filter the first array, then use array_diff filter the second:
$specificIndex = array('index1', 'index3');
$array1 = array_diff_key($array, array_flip($specificIndex));
$array2 = array_diff($array, $array1);
Demo.
If you want get in an array only certain elements of your choice you can do something like:
$specificIndex = array('index1', 'index3');
$selectedItem = array_intersect_key($array, array_flip($specificIndex));
Demo.
<?php
$array = array(
'index1' => 'Deleted',
'index2' => 'numbers',
'index3' => 'test',
'index4' => 'Inserted',
);
$specificIndex = 'index3';
$array1=array();
foreach($array as $key => $value){
if($key==$specificIndex){
$array1[$key] = $value;
unset($array[$specificIndex]);
}
}
print_r($array);
print_r($array1);
http://3v4l.org/TvZ19
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);
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
)
)