recursive function to remove '<' and '>' from array keys - php

I'm trying to get an xml file from an associative array having array keys encapsuled into '<' and '>'
I've tried to use a recursive function but it works correctly only on the first level:
Please remember my final goal is to create an xml, so any appropriate suggest is welcome
this is what I've done so far:
$arr =
array('<Lev0_0>' => 0,
'<Lev0_1>' => 1,
'<Lev0_2>' => array (
'<Lev1_0>' => 2,
'<Lev1_1>' => 3
)
);
print_r(RepairKeysMultidimensional($arr));
function RepairKeysMultidimensional(array $array){
$Keys = array();
foreach($array as $Key => $Value){
$NewKey = str_replace(array('<','>'),'',$Key);
$array[$NewKey] = $Value;
unset($array[$Key]);
if(is_array($Value)){
RepairKeysMultidimensional($Value);
}
}
return $array;
}
the output is:
Array (
[Lev0_0] => 0
[Lev0_1] => 1
[Lev0_2] => Array (
[] => 2
[] => 3
)
)

If that's the structure and you never expect < or > as part of the values, you don't need to loop over it just json_encode it, strip out the chars and the json_decode it back into an array.
<?php
$arr = array(
'<Lev0_0>' => 0,
'<Lev0_1>' => 1,
'<Lev0_2>' => array (
'<Lev1_0>' => 2,
'<Lev1_1>' => 3
)
);
$arr = json_decode(str_replace(array('<','>'), '', json_encode($arr)), true);
print_r($arr);
https://3v4l.org/2d7Hq
Result:
Array
(
[Lev0_0] => 0
[Lev0_1] => 1
[Lev0_2] => Array
(
[Lev1_0] => 2
[Lev1_1] => 3
)
)

Try to add affectation in your if statement:
function RepairKeysMultidimensional(array $array){
$Keys = array();
foreach($array as $Key => $Value){
$NewKey = str_replace(array('<','>'),'',$Key);
$array[$NewKey] = $Value;
unset($array[$Key]);
if (is_array($Value)) {
$array[$NewKey] = RepairKeysMultidimensional($Value);
}
}
return $array;
}

you are not affecting the result of the second call to the outer array!
Try this :
<?php
$arr =
array('<Lev0_0>' => 0,
'<Lev0_1>' => 1,
'<Lev0_2>' => array (
'<Lev1_0>' => 2,
'<Lev1_1>' => 3
)
);
echo str_replace(array('<','>'),'','<Lev0>');
echo '<br/><br/>';
print_r(RepairKeysMultidimensional($arr));
function RepairKeysMultidimensional(array $array){
$Keys = array();
foreach($array as $Key => $Value){
$NewKey = str_replace(array('<','>'),'',$Key);
unset($array[$Key]);
if(is_array($Value)){
$array[$NewKey] = RepairKeysMultidimensional($Value);
}else{
$array[$NewKey] = $Value;
}
}
return $array;
}
The output of this is :
Array (
[Lev0_0] => 0
[Lev0_1] => 1
[Lev0_2] => Array (
[Lev1_0] => 2
[Lev1_1] => 3 ) )

Related

How to convert multi-dimensional array into single array using PHP?

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

Update Multidimentional Array with another Array for existing Keys PHP

I have two arrays:
('admin','admin2', 'admin3' can be too many, and names can also differ other than 'admin')
$old = array(
array('admin'=>array('a'=>'aaa','b'=>'bbb')),
array('admin2'=>array('c'=>'ccc','d'=>'ddd'))
);
$new = array(
array('admin2'=>array('e'=>'eee','f'=>'fff')),
array('admin3'=>array('g'=>'ggg','h'=>'hhh'))
);
I want to have this array from both above arrays:
(new array with all different keys in both PLUS similar keys from new array)
$output = array(
array('admin'=>array('a'=>'aaa','b'=>'bbb')),
array('admin2'=>array('e'=>'eee','f'=>'fff')),
array('admin3'=>array('g'=>'ggg','h'=>'hhh'))
);
// Remove one level of array to make arrays as ['admin'=>array, 'admin2'=>array]
$old1 = call_user_func_array('array_merge', $old);
$new1 = call_user_func_array('array_merge', $new);
// Make replacement
$ready = array_replace($old1, $new1);
// Return level making every item as array
$result = array();
foreach($ready as $k=>&$v)
$result[] = array($k=>$v);
print_r($result);
demolink
This code will solve your problem :
<?php
$array1 = array(
array('admin'=>array('a'=>'aaa','b'=>'bbb')),
array('admin2'=>array('c'=>'ccc','d'=>'ddd'))
);
$array2 = array(
array('admin2'=>array('e'=>'eee','f'=>'fff')),
array('admin3'=>array('g'=>'ggg','h'=>'hhh'))
);
$output = $array1; ///merge array1 into output array
foreach($array2 as $key => $val)
{
$is_present_key = false;
$first_key = key($val);
foreach($output as $k => $v)
{
if(array_key_exists($first_key,$output[$k])) ////check if key exit in $output array
{
$output[$k] = $val; ///push new value if key exists in $output
$is_present_key = true;
}
}
if($is_present_key == false)///skip for duplicate of new values if key exists in $output
{
$output[] = $val;
}
}
echo "<pre>"; print_r($output);
?>
This will give you :
Array
(
[0] => Array
(
[admin] => Array
(
[a] => aaa
[b] => bbb
)
)
[1] => Array
(
[admin2] => Array
(
[e] => eee
[f] => fff
)
)
[2] => Array
(
[admin3] => Array
(
[g] => ggg
[h] => hhh
)
)
)
LIVE EXAMPLE
$old = array(
array('admin'=>array('a'=>'aaa','b'=>'bbb')),
array('admin2'=>array('c'=>'ccc','d'=>'ddd'))
);
$new = array(
array('admin2'=>array('e'=>'eee','f'=>'fff')),
array('admin3'=>array('g'=>'ggg','h'=>'hhh'))
);
$arr=array_merge($new,$old);
$new_arr=array();
foreach($arr as $key=>$val){
foreach($val as $k=>$v){
if(array_key_exists($k, $new_arr)){
continue;
}else{
$new_arr[$k]=$v;
}
}
}
echo "<pre>";print_r($new_arr); echo "</pre>";

Get only Numeric values from Array in PHP

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); }
}

transfer specific index of array to a new array - php

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

need to search for values in each string of an array to construct another array

I have this array:
Array
(
[count] => 12
[6] => CN=G_Information_Services,CN=Users,DC=hccc,DC=campus
[7] => CN=WEBadmin,CN=Users,DC=hccc,DC=campus
[9] => CN=G_ISDept,CN=Users,DC=hccc,DC=campus
[10] => CN=STAFF,CN=Users,DC=hccc,DC=campus
)
and I want to create an array of values that consist of the value between the first CN= and , of each array value below.
I probably will have to loop thru the array above, do a regex search for the first occurrence of cn and the value that follows it
I am not sure what I am doing wrong.
I need the final result to be an array that resembles this:
array('G_Information_Services', 'WEBadmin', 'G_ISDept', 'STAFF');
Use preg_match on each of the array values to get only the first corresponding CN value.
$found = array();
foreach ($arr AS $values) {
if (preg_match('/CN=([^,]+),/',$values,$matches))
$found[] = $matches[1];
}
Output
Array
(
[0] => G_Information_Services
[1] => WEBadmin
[2] => G_ISDept
[3] => STAFF
)
Try this (not the most efficient way but it should work):
foreach ($array as $key => $value)
{
if (is_numeric($key))
{
$array[$key] = explode(',', $array[$key]);
$array[$key] = $array[$key][0];
$array[$key] = substr($array[$key], 3);
}
}
This gets the first value of CN= of each element of the array, it also ignores any DC= values.
$arr = array(
'count' => 12,
6 => 'CN=G_Information_Services,CN=Users,DC=hccc,DC=campus',
7 => 'CN=WEBadmin,CN=Users,DC=hccc,DC=campus',
9 => 'CN=G_ISDept,CN=Users,DC=hccc,DC=campus',
10 => 'CN=STAFF,CN=Users,DC=hccc,DC=campus'
);
$newArr = array();
foreach($arr as $key => $value)
{
if($key != 'count')
{
$temp = explode(',', $value);
foreach($temp as $item)
{
if(strpos($item, 'CN=') === 0)
{
$item = substr($item, 3 );
$newArr[] = $item;
break 1;
}
}
}
}
print_r($newArr);

Categories