I have this array $arr1
Array
(
[0] => [col1]
[1] => [col2]
[2] => [col3]
)
I have another array $arr2 as
Array
(
[0] => Array
(
[col3] => data1
[col2] => data2
[col1] => data3
)
[1] => Array
(
[col2] => data1
[col3] => data2
[col1] => data3
)
)
I need to sort this $arr2 keys as col1, col2 and col3 like as it is on $arr1.
I tried with array_multisort($arr1,$arr2) and the other way. Nothing worked. any help on this ?
Using loop.
$keys = array_values($arr1);
$out = array();
foreach($arr2 as $ar){
$outar = array();
foreach($keys as $k){
if(isset($ar[$k])){
$outar[$k]=$ar[$k];
}
}
$out[]=$outar;
}
The output array will be held in $out. See ideone.
You can do this with uksort and a closure (PHP 5.3+)
foreach($arr2 as &$array){
uksort($array,function($a,$b) use ($arr1){
return array_search($a, $arr1) - array_search($b, $arr1);
});
}
foreach ( $arr2 as $k => &$arr ) {
ksort($arr);
}
print_r($arr2);
Use ksort with a foreach loop with value passed by reference.
if first array values are exactly the same as indexes in second one, try
$resarr = array();
foreach ($arr2 as $somearr) {
$i = 0;
$newarr = array();
foreach ($somearr as $value) {
$newarr[$arr1[$i]] = $value;
$i++;
}
$resarr[] = $newarr;
}
$arr1 = $resarr;
Related
I have an array, whose structure is basically like this:
array('id,"1"', 'name,"abcd"', 'age,"30"')
I want to convert it into a two dimensional array, which has each element as key -> value:
array(array(id,1),array(name,abcd),array(age,30))
Any advice would be appreciated!
I tried this code:
foreach ($datatest as $lines => $value){
$tok = explode(',',$value);
$arrayoutput[$tok[0]][$tok[1]] = $value;
}
but it didn't work.
Assuming you want to remove all quotation marks as per your question:
$oldArray = array('id,"1"', 'name,"abcd"', 'age,"30"')
$newArray = array();
foreach ($oldArray as $value) {
$value = str_replace(array('"',"'"), '', $value);
$parts = explode(',', $value);
$newArray[] = $parts;
}
You can do something like this:
$a = array('id,"1"', 'name,"abcd"', 'age,"30"');
$b = array();
foreach($a as $first_array)
{
$temp = explode("," $first_array);
$b[$temp[0]] = $b[$temp[1]];
}
$AR = array('id,"1"', 'name,"abcd"', 'age,"30"');
$val = array();
foreach ($AR as $aa){
$val[] = array($aa);
}
print_r($val);
Output:
Array ( [0] => Array ( [0] => id,"1" ) [1] => Array ( [0] => name,"abcd" ) [2] => Array ( [0] => age,"30" ) )
With array_map function:
$arr = ['id,"1"', 'name,"abcd"', 'age,"30"'];
$result = array_map(function($v){
list($k,$v) = explode(',', $v);
return [$k => $v];
}, $arr);
print_r($result);
The output:
Array
(
[0] => Array
(
[id] => "1"
)
[1] => Array
(
[name] => "abcd"
)
[2] => Array
(
[age] => "30"
)
)
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 have two arrays and I want to replace the second array keys with the first array values if both keys matches.
As an example: Replace A with Code And B with name
How to do this;
<?php
$array = array('A' => 'code', 'B' =>'name');
$replacement_keys = array
(
array("A"=>'sara','B'=>2020),
array("A"=>'ahmed','B'=>1010)
);
foreach($replacement_keys as $key => $value){
foreach($value as $sk => $sv){
foreach($array as $rk => $rv){
if($sk == $rk ){
$sk = $rv;
}
}
}
}
echo "<pre>";
print_r($value);
echo "</pre>";
exit;
I want the result to be like this
array(
[0] => Array
(
[name] => ahmed
[code] => 1020
)
[1] => Array
(
[name] => sara
[code] => 2020
)
)
<?php
$array = array('A' => 'code', 'B' =>'name');
$replacement_keys = array
(
array("A"=>'sara','B'=>2020),
array("A"=>'ahmed','B'=>1010)
);
foreach($replacement_keys as &$value)
{
foreach ($array as $key => $name) {
$value[$name] = $value[$key];
unset($value[$key]);
}
}
var_dump($replacement_keys);
Try this:
<?php
$array = array('A' => 'code', 'B' =>'name');
$replacement_keys = array
(
array("A"=>'sara','B'=>2020),
array("A"=>'ahmed','B'=>1010)
);
$newArray = array();
foreach($replacement_keys as $key => $value)
{
foreach($value as $key2 => $value2)
{
if(isset($array[$key2]))
{
$newArray[$key][$array[$key2]] = $value2;
}
else
{
$newArray[$key][$key2] = $value2;
}
}
}
print_R($newArray);
This should work for you, nice and simple (I'm going to assume that A should be name and B should be code):
(Here I go through each array from $replacement_keys with array_map() and replace the array_keys() with the array_values() of $array. Then I simply get all array values from $replacement_keys and finally I array_combine() the replaced array keys with the corresponding array values)
$result = array_map("array_combine",
array_map(function($v)use($array){
return str_replace(array_keys($array), array_values($array), array_keys($v));
}, $replacement_keys),
$replacement_keys
);
output:
Array ( [0] => Array ( [code] => sara [name] => 2020 ) [1] => Array ( [code] => ahmed [name] => 1010 ) )
array_fill_keys
(PHP 5 >= 5.2.0, PHP 7)
array_fill_keys — Fill an array with values, specifying keys
Description
array array_fill_keys ( array $keys , mixed $value )
Fills an array with the value of the value parameter, using the values of the keys array as keys.
http://php.net/manual/en/function.array-fill-keys.php
When print_r($my_array);
Array
(
[0] => Array
(
[value] => num1
[label] =>
)
[1] => Array
(
[value] => num2
[label] =>
)
[2] => Array
(
[value] => num3
[label] =>
)
)
Now I wonder how to create a new array variable to hold only 1 level with the following structure. e.g:
if print_r($new_array), it will show:
Array
(
[0] => num1
[1] => num2
[2] => num3
)
Try foreach() and store value in new array
foreach($arr as $v) {
$newarr[] = $v['value'];
}
print_r($newarr);
$new = array_map(function($element){ return $element['value'] ; }, $array);
Try with foreach of $my_array and assign value to $new_array variable like
$new_array = array();
foreach($my_array as $array){
$new_array[] = $array['value'];
}
print_r($new_array);
Loop thru the array as follows and push the desired elements into a new array.
$new_array = array();
for($i=0;$i<count($my_array);$i++) {
array_push($new_array, $my_array[$i]['value']);
}
print_r($new_array);
below can work:
foreach($my_array as $k => $v){
$new_array[] = $v['value'];
}
print_r($new_array);
$new_array = array();
foreach ($my_array as $key => $value) {
$new_array[] = $value['value'];
}
print_r($new_array);