Build multidimensional array from keys - php

I can't seem to figure this out and I'm hoping someone has a magical recursive solution to this. I have a list of keys and basically I want to transform it into a nested array.
array('level1', 'level2', 'level3');
To
array(
'level1' => array(
'level2' => array(
'level3' // last key in array should be just a value
)
)
)
Much appreciation to anyone who can help!

Something like this should do the job:
function buildMultiDimensional(Array $arr)
{
// the first value will become a new key
$newKey = array_shift($arr);
if (empty($arr)) {
// this is where the recursion stops
return $newKey;
}
// and the recursion !!!
return array($newKey => buildMultiDimensional($arr));
}
$arr = array('level1', 'level2', 'level3', 'level4', 'level5');
var_dump(buildMultiDimensional($arr));
The result is what's expected:
array(1) {
["level1"]=>
array(1) {
["level2"]=>
array(1) {
["level3"]=>
array(1) {
["level4"]=>
string(6) "level5"
}
}
}
}

You don't need recursion. A single loop is fine with references.
<?php
//array to iterate
$array = array('level1', 'level2', 'level3');
//contains our entire array
$out = array();
//temp variable to store references as we go down.
$tmp = &$out;
//get the last value off the array
$last = array_pop($array);
//loop over the array
foreach($array as $level){
//make an array under the current level
$tmp[$level] = array();
//assign tmp to the new level
$tmp = &$tmp[$level];
}
//assign the last key as the value under the last key
$tmp = $last;
//display output
print_r($out);
example: http://codepad.viper-7.com/zATfyo
And without references, working in reverse:
<?php
//array to iterate
$array = array('level1', 'level2', 'level3');
//get the last value off the array
$out = array_pop($array);
//flip the array backwards
$array = array_reverse($array);
//loop over the array
foreach($array as $level){
$out = array($level=>$out);
}
//display output
print_r($out);
Example: http://codepad.viper-7.com/fgxeHO

Related

PHP - Searching in multidimensional array

i'm in a lot of brain-pain, please advise. I have the following situation:
i have the next multidimensional array:
$numbers = array (
"one_digit" => array (1,2,3,4,5),
"two_digits" => array (20,21,22,23,24,25),
"three_digits" => array (301,302,303,304,304),
"mixed_digits" => array (9,29,309,1)
);
i need a way to search in the $numbers array for the following:
-- search if number 20 is in any $numbers array and echo where it is found
ex. $find1 = m_array_search("20", $numbers); echo "i've found the searched value in ".$find1." subarray of $numbers";
result: "i've found the searched value in two_digits subarray of $numbers"
-- search if number 1 is in any $numbers array and echo where it is found
ex. $find2 = m_array_search("1", $numbers); echo "i've found the searched value in ".$find2." subarray of $numbers";
result: "i've found the searched value in two_digits,mixed_digits subarray of $numbers"
thus function must be able to spot presence in one or many "subarrays". sorry if i've missued the term "subarray"
THANK YOU!!!
Simple solution using in_array function:
$search = 1;
$keys = [];
foreach ($numbers as $k => $v) {
if (is_array($v) && in_array($search, $v)) $keys[] = $k;
}
echo "I've found the searched value in ". implode(', ', $keys) ." subarray". ((count($keys) > 1)? "s":"") ." of \$numbers";
The output:
I've found the searched value in one_digit, mixed_digits subarrays of $numbers
Check this and let me know if it helps you .
<?php
function array_find_deep($array, $search, $keys = array())
{
foreach($array as $key => $value) {
if (is_array($value)) {
$sub = array_find_deep($value, $search, array_merge($keys, array($key)));
if (count($sub)) {
return $sub;
}
} elseif ($value === $search) {
return array_merge($keys, array($key));
}
}
return array();
}
$numbers = array (
"one_digit" => array (1,2,3,4,5),
"two_digits" => array (20,21,22,23,24,25),
"three_digits" => array (301,302,303,304,304),
"mixed_digits" => array (9,29,309,1)
);
var_dump(array_find_deep($numbers, 20));
var_dump(array_find_deep($numbers, 1));
var_dump(array_find_deep($numbers, 301));
var_dump(array_find_deep($numbers, 309));
?>
You can store the result in a variable like $result = array_find_deep($numbers, 20); and try echo $result[0] which will give the result that in which array it found the value.
You can try this with array_search() in a loop -
$numbers = array (
"one_digit" => array (1,2,3,4,5),
"two_digits" => array (20,21,22,23,24,25),
"three_digits" => array (301,302,303,304,304),
"mixed_digits" => array (9,29,309,1)
);
function search_value($array, $value)
{
$result = array();
foreach($array as $key => $sub) {
// check if element present in sub array
if(array_search($value, $sub) !== false) {
// store the key
$result[] = $key;
}
}
return $result;
}
var_dump(search_value($numbers, 1));
var_dump(search_value($numbers, 5));
Output
array(2) {
[0]=>
string(9) "one_digit"
[1]=>
string(12) "mixed_digits"
}
array(1) {
[0]=>
string(9) "one_digit"
}

PHP return second value of 2D array

I have the following PHP code:
$special_files = array(
array("Turnip", "Tweed"),
array("Donald", "Trump")
);
I want to be able to get the second value in a nested array by identifying a first. eg: if_exists("Donald") would return "trump".
I've tried to recurse through the array but I'm at a loss on how to select the second value once the first is identified.
Any help would be appreciated
You can use something like this:
$special_files = array(
array("Turnip", "Tweed"),
array("Donald", "Trump")
);
$search_val = "Donald";
$key = array_search($search_val, array_column($special_files,0));
$output = $special_files[$key][1]; //outputs "Trump"
Here is a working sample.
Well, you can try the following:
foreach ($special_files as $special_file) {
$i = 1;
foreach ($special_file as $element) {
if ($i==2) {
echo ("Second value is: " . $element);
break;
}
$i++;
}
}
You can extract the [1] elements and index them by the [0] elements:
$lookup = array_column($special_files, 1, 0);
$result = isset($lookup['Donald']) ?: false;
The $lookup array yields:
Array
(
[Turnip] => Tweed
[Donald] => Trump
)

How to create an array based on value in PHP?

I have an array like this
Array
(
[0] => 123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-31).pdf
[1] => 123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-30).pdf
[2] => 123_bms_for__on__(10-06-2015_18-36).pdf
)
I want to convert this into multidimensional array based on its value such
as
Array
(
[dr] => Array
(
[0] => 123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-31).pdf
[1] => 123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-30).pdf
)
[bms] => Array
(
[0] => 123_bms_for__on__(10-06-2015_18-36).pdf
)
)
based on name after first underscore (bms,dr) like....... Please help me to achieve this
I would do the following:
$newArray = array();
foreach ($array as $key => $value) {
$parts = explode('_', $value);
$newArray[$parts[1]][] = $value;
}
print_r($newArray);
To solve this without a loop, it would be smart to use a function along with built in Array Filter function.
Here's another possible solution - which seems a little cooler I suppose;
<?php
// ####################
// GLOBAL VARIABLES DEFINITION
// ####################
// Store Pattern Here = Used to Define Array at the end
global $Array_IDs;
$Array_IDs = array();
// Store Variables With Header Pattern (ID) in this area
global $Array_Values;
$Array_Values = array();
// ####################
// FUNCTION DEFINITION
// ####################
// FUNCTION TO SPLIT ARRAY
function Get_ID($variable){
// ACCESS GLOBALS
global $Array_IDs;
global $Array_Values;
// GET CURRENT VARIBALE - EXPLODE TO EXTRACT PATTERN AS ID
$Temp_Parts = explode("_", $variable);
// CHECK IF IDENTIFIER IS ALREADY FOUND (STORED IN ARRAY_ID)
if (in_array($Temp_Parts[1], $Array_IDs)){
// ID ALREADY HAS SUB-ARRAY CREATED
// JUST APPEND VARIABLE
$Array_Values[$Temp_Parts[1]][] = $variable;
}else{
// ADD ID TO Array_IDs
$Array_IDs[] = $Temp_Parts[1];
// Create New ARRAY with HEADER AS PATTERN - ID
$Array_Values[$Temp_Parts[1]][] = $variable;
}
}
// ####################
// CODE STARTS HERE == ONLY THREE LINES ;)
// ####################
$Start_Array = array('123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-31).pdf','123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-30).pdf','123_bms_for__on__(10-06-2015_18-36).pdf');
array_filter($Start_Array,"Get_ID");
print_r($Array_Values);
?>
Give it a try and let me know how it goes, the output is as requested ;)
You can use array_reduce function and regex matching for elegant & lesser code.
$array = array(
'0'=>'123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-31).pdf',
'1'=>'123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-30).pdf',
'2'=>'123_bms_for__on__(10-06-2015_18-36).pdf'
);
$result = array_reduce($array, function($prod, $current){
preg_match('/(?<=^123_)\w+(?=_for\w+)/',$current,$match);
$prod[$match[0]][] = $current;
return $prod;
}, []);
Will produce the following result.
array(2) {
[0]=>
string(57) "123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-31).pdf"
[1]=>
string(57) "123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-30).pdf"
}
array(1) {
[0]=>
string(39) "123_bms_for__on__(10-06-2015_18-36).pdf"
}
Using square bracket require PHP 5.4 above, you can replace with array() instead for lower version of PHP.
please find below code as per your requirement.
<?php
$array = array(
'0'=>'123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-31).pdf',
'1'=>'123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-30).pdf',
'2'=>'123_bms_for__on__(10-06-2015_18-36).pdf'
);
$dr_array = array();
$bms_array = array();
foreach($array as $val){
$str_explode = explode("_",$val);
if($str_explode[1]=="dr"){
$dr_array[] = $val;
}
else if($str_explode[1]=="bms"){
$bms_array[] = $val;
}
}
var_dump($dr_array);
var_dump($bms_array);
?>
Output :
array(2) {
[0]=>
string(57) "123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-31).pdf"
[1]=>
string(57) "123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-30).pdf"
}
array(1) {
[0]=>
string(39) "123_bms_for__on__(10-06-2015_18-36).pdf"
}
Thanks.
$basicArray = array(); //It Stores All The Elements
$firstArray = array(); //It will store array elements of first type
$secondArray = array(); //It will store array elements of second type
for($i = 0; $i < count($basicArray); $i++)
{
$elementArray = explode("_", $basicArray[i]);
if($elementArray[1] == "dr")
array_push($firstArray, $basicArray[i]);
else if($elementArray[1] == "bms")
array_push($secondArray, $basicArray[i]);
}
$finalArray = array();
array_push($finalArray, $firstArray, $secondArray);

Compare and replace values in array

I need compare 2 arrays , the first array have one order and can´t change , in the other array i have different values , the first array must compare his id with the id of the other array , and if the id it´s the same , take the value and replace for show all in the same order
For Example :
$array_1=array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2=array("4a-walking","2a-cats");
The Result in this case i want get it´s this :
"1a-dogs","2a-cats","3a-birds","4a-walking"
If the id in this case 4a it´s the same , that entry must be modificate and put the value of other array and stay all in the same order
I do this but no get work me :
for($fte=0;$fte<count($array_1);$fte++)
{
$exp_id_tmp=explode("-",$array_1[$fte]);
$cr_temp[]="".$exp_id_tmp[0]."";
}
for($ftt=0;$ftt<count($array_2);$ftt++)
{
$exp_id_targ=explode("-",$array_2[$ftt]);
$cr_target[]="".$exp_id_targ[0]."";
}
/// Here I tried use array_diff and others but no can get the results as i want
How i can do this for get this results ?
Maybe you could use the array_udiff_assoc() function with a callback
Here you go. It's not the cleanest code I've ever written.
Runnable example: http://3v4l.org/kUC3r
<?php
$array_1=array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2=array("4a-walking","2a-cats");
function getKeyStartingWith($array, $startVal){
foreach($array as $key => $val){
if(strpos($val, $startVal) === 0){
return $key;
}
}
return false;
}
function getMergedArray($array_1, $array_2){
$array_3 = array();
foreach($array_1 as $key => $val){
$startVal = substr($val, 0, 2);
$array_2_key = getKeyStartingWith($array_2, $startVal);
if($array_2_key !== false){
$array_3[$key] = $array_2[$array_2_key];
} else {
$array_3[$key] = $val;
}
}
return $array_3;
}
$array_1 = getMergedArray($array_1, $array_2);
print_r($array_1);
First split the 2 arrays into proper key and value pairs (key = 1a and value = dogs). Then try looping through the first array and for each of its keys check to see if it exists in the second array. If it does, replace the value from the second array in the first. And at the end your first array will contain the result you want.
Like so:
$array_1 = array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2 = array("4a-walking","2a-cats");
function splitArray ($arrayInput)
{
$arrayOutput = array();
foreach ($arrayInput as $element) {
$tempArray = explode('-', $element);
$arrayOutput[$tempArray[0]] = $tempArray[1];
}
return $arrayOutput;
}
$arraySplit1 = splitArray($array_1);
$arraySplit2 = splitArray($array_2);
foreach ($arraySplit1 as $key1 => $value1) {
if (array_key_exists($key1, $arraySplit2)) {
$arraySplit1[$key1] = $arraySplit2[$key1];
}
}
print_r($arraySplit1);
See it working here:
http://3v4l.org/2BrVI
$array_1=array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2=array("4a-walking","2a-cats");
function merge_array($arr1, $arr2) {
$arr_tmp1 = array();
foreach($arr1 as $val) {
list($key, $val) = explode('-', $val);
$arr_tmp1[$key] = $val;
}
foreach($arr2 as $val) {
list($key, $val) = explode('-', $val);
if(array_key_exists($key, $arr_tmp1))
$arr_tmp1[$key] = $val;
}
return $arr_tmp1;
}
$result = merge_array($array_1, $array_2);
echo '<pre>';
print_r($result);
echo '</pre>';
This short code works properly, you'll get this result:
Array
(
[1a] => dogs
[2a] => cats
[3a] => birds
[4a] => walking
)

Creating array from string

I need to create array like that:
Array('firstkey' => Array('secondkey' => Array('nkey' => ...)))
From this:
firstkey.secondkey.nkey.(...)
$yourString = 'firstkey.secondkey.nkey';
// split the string into pieces
$pieces = explode('.', $yourString);
$result = array();
// $current is a reference to the array in which new elements should be added
$current = &$result;
foreach($pieces as $key){
// add an empty array to the current array
$current[ $key ] = array();
// descend into the new array
$current = &$current[ $key ];
}
//$result contains the array you want
My take on this:
<?php
$theString = "var1.var2.var3.var4";
$theArray = explode(".", $theString); // explode the string into an array, split by "."
$result = array();
$current = &$result; // $current is a reference to the array we want to put a new key into, shifting further up the tree every time we add an array.
while ($key = array_shift($theArray)){ // array_shift() removes the first element of the array, and assigns it to $key. The loop will stop as soon as there are no more items in $theArray.
$current[$key] = array(); // add the new key => value pair
$current = &$current[$key]; // set the reference point to the newly created array.
}
var_dump($result);
?>
With an array_push() in the while loop.
What do you want the value of the deepest key to be?
Try something like:
function dotToArray() {
$result = array();
$keys = explode(".", $str);
while (count($keys) > 0) {
$current = array_pop($keys);
$result = array($current=>$result);
}
return $result;
}

Categories