PHP - multidimensional array to query string - php

Searched for so long but didn't get any feasible answer.
A) Input:
$array = array(
'order_source' => array('google','facebook'),
'order_medium' => 'google-text'
);
Which looks like:
Array
(
[order_source] => Array
(
[0] => google
[1] => facebook
)
[order_medium] => google-text
)
B) Required output:
order_source=google&order_source=facebook&order_medium=google-text
C) What I've tried (http://3v4l.org/b3OYo):
$arr = array('order_source' => array('google','facebook'), 'order_medium' => 'google-text');
function bqs($array, $qs='')
{
foreach($array as $par => $val)
{
if(is_array($val))
{
bqs($val, $qs);
}
else
{
$qs .= $par.'='.$val.'&';
}
}
return $qs;
}
echo $qss = bqs($arr);
D) What I'm getting:
order_medium=google-text&
Note: It should also work for any single dimensional array like http_build_query() works.

I hope that this is what you are looking for, it works with single to n-dimensinal arrays.
$walk = function( $item, $key, $parent_key = '' ) use ( &$output, &$walk ) {
is_array( $item )
? array_walk( $item, $walk, $key )
: $output[] = http_build_query( array( $parent_key ?: $key => $item ) );
};
array_walk( $array, $walk );
echo implode( '&', $output ); // order_source=google&order_source=facebook&order_medium=google-text

You don't really need to do anything special here.
$array = array(
'order_source' => array('google', 'facebook'),
'order_medium' => 'google-text'
);
$qss = http_build_query($array);
On the other side:
var_dump($_GET);
Result:
array(2) {
["order_source"]=>
array(2) {
[0]=>
string(6) "google"
[1]=>
string(8) "facebook"
}
["order_medium"]=>
string(11) "google-text"
}
This really is the best way to send arrays as GET variables.
If you absolutely must have the output as you've defined, this will do it:
function bqs($array, $qs = false) {
$parts = array();
if ($qs) {
$parts[] = $qs;
}
foreach ($array as $key => $value) {
if (is_array($value)) {
foreach ($value as $value2) {
$parts[] = http_build_query(array($key => $value2));
}
} else {
$parts[] = http_build_query(array($key => $value));
}
}
return join('&', $parts);
}

Although as you found in the comments if you are trying to pass this as $_GET you will have override problems, the solution to your problem to get desired results using recursive functions would be:
function bqs($array, $qs='',$index = false)
{
foreach($array as $par => $val)
{
if($index)
$par = $index;
if(is_array($val))
{
$qs = bqs($val, $qs,$par);
}
else
{
$qs .= $par.'='.$val.'&';
}
}
return $qs;
}
where i am concatinating the $qs string if it's an array and passing the index as a reference along with the value if it's an array()
fixed
After supplying the $index you do not need to concatenate again. See here: http://3v4l.org/QHF5G

Related

Search array by key branch

I have an array that looks like this:
$array = array (
[level_1] => array (
[level_2] => array (
[level_3] => something
)
),
[level_12] => array (
[level_2] => somethingelse
),
[level_13] => array (
[level_22] => array (
[level_3] => something
)
),
);
The keys or values aren't always unique but the branches are.
And I have a string that looks like this:
$string = 'level_1-level_2-level_3';
Those are the keys for a branch.
And I need to somehow get the value from the array based on that string?
Like this:
$string_array = explode('-', $string);
$array[$string_array[0]][$string_array[1]][$string_array[2]] // something
But since the depth can be different this is not a viable solution...
Try this simple example, no need for a recursive function:
function get_item( $path, $array )
{
$paths = explode( '-', $path );
$result = $array;
foreach ( $paths as $path) {
isset( $result[$path] ) ? $result = $result[$path] : $result = false;
}
return $result;
}
$path = 'level_1-level_2-level_3';
echo get_item( $path, $array );
Try this:
$array = array (
'level_1' => array (
'level_2' => array (
'level_3' => 'something'
)
),
'level_12' => array (
'level_2' => 'somethingelse'
),
'level_13' => array (
'level_22' => array (
'level_3' => 'something'
)
),
);
$string = 'level_1-level_2-level_3';
$keys = explode('-', $string);
echo getItemIterative($keys, $array);
echo "\n";
echo getItemRecursive($keys, $array);
function getItemIterative($keys, $array)
{
$value = null;
foreach ($keys as $key) {
if ($value == null) {
$value = $array[$key];
}
if (is_array($value) && array_key_exists($key, $value)) {
$value = $value[$key];
}
}
return $value;
}
function getItemRecursive($keys, $array)
{
$key = array_shift($keys);
$value = $array[$key];
if (empty($keys)) {
return $value;
} else {
return getItemRecursive($keys, $value);
}
}
Make a $result variable which initially points to the root of the array, and loop through the levels of your $string_array 'til $result points at the leaf you were looking for.
// stuff you already have:
$array = array(...); // your big array
$string = 'level_1-level_2-level_3';
$string_array = explode('-', $string);
// new stuff:
$result = $array;
foreach ($string_array as $level) {
$result = $result[$level];
}
echo $result; // 'something'
Working example: Ideone

Reverse flatted array to multidimensional

In another thread i asked about flatten an array with a specific style to get something like this:
array(4) {
["one"]=> string(9) "one_value"
["two-four"]=> string(10) "four_value"
["two-five"]=> string(10) "five_value"
["three-six-seven"]=> string(11) "seven_value"
}
I've got some very good help there, but now im wondering how would i reverse this method to get again the same original array:
array(
'one' => 'one_value',
'two' => array
(
'four' => 'four_value',
'five' => 'five_value'
),
'three' => array
(
'six' => array
(
'seven' => 'seven_value'
)
)
)
I've tried with recursive method but with no luck.
I thank all the help in advance!
function expand($flat) {
$result = array();
foreach($flat as $key => $val) {
$keyParts = explode("-", $key);
$currentArray = &$result;
for($i=0; $i<count($keyParts)-1; $i++) {
if(!isSet($currentArray[$keyParts[$i]])) {
$currentArray[$keyParts[$i]] = array();
}
$currentArray = &$currentArray[$keyParts[$i]];
}
$currentArray[$keyParts[count($keyParts)-1]] = $val;
}
return $result;
}
Note that the code above is not tested and is given only to illustrate the idea.
The & operator is used for $currentArray to store not the value but the reference to some node in your tree (implemented by multidimensional array), so that changing $currentArray will change $result as well.
Here is an efficient recursive solution:
$foo = array(
"one" => "one_value",
"two-four" => "four_value",
"two-five" => "five_value",
"three-six-seven" => "seven_value"
);
function reverser($the_array) {
$temp = array();
foreach ($the_array as $key => $value) {
if (false != strpos($key, '-')) {
$first = strstr($key, '-', true);
$rest = strstr($key, '-');
if (isset($temp[$first])) {
$temp[$first] = array_merge($temp[$first], reverser(array(substr($rest, 1) => $value)));
} else {
$temp[$first] = reverser(array(substr($rest, 1) => $value));
}
} else {
$temp[$key] = $value;
}
}
return $temp;
}
print_r(reverser($foo));
strstr(___, ___, true) only works with PHP 5.3 or greater, but if this is a problem, there's a simple one-line solution (ask if you'd like it).

Search and replace inside an associative array

I need to search and replace inside an associative array.
ex:
$user = "user1"; // I've updated this
$myarray = array("user1" => "search1", "user2" => "search2", "user3" => "search1" ) ;
I want to replace search1 for search4. How can I achieve this?
UPDATE: I forgot to mention that the array has several search1 values and I just want to change the value where the key is == $user. Sorry for not mention this earlier.
$myarray = array("user1" => "search1", "user2" => "search2" );
foreach($myarray as $key => $val)
{
if ($val == 'search1') $myarray[$key] = 'search4';
}
There's a function for this : array_map().
// Using a lamba function, PHP 5.3 required
$newarray = array_map(
function($v) { if ($v == 'search1') $v = 'search4'; return $v; },
$myarray
);
If you don't want to use a lambda function, define a normal function or method and callback to it.
Why not just do
if (isset($myarray[$user])) $myarray[$user] = 'search4';
$user = "user1";
$myarray = array("user1" => "search1", "user2" => "search2", "user3" => "search1" );
foreach($myarray as $key => $val)
{
if ($val == 'search1' and $key == $user )
{
$myarray[$key] = 'search4';
break;
}
}
print_r($myarray);
Prints:
Array
(
[user1] => search4
[user2] => search2
[user3] => search1
)
$originalArray = array( "user1" => "search1" , "user2" => "search2" );
$pattern = 'search1';
$replace = 'search4';
$replacedArray = preg_replace( '/'.$pattern.'/' , $replace , $originalArray );
Fixes the risk mentioned in comment in response to this solution
Updated
Since the post was updated, and I have had chance to get some sleep, I realized my answer was stupid. If you have a given key and you need to change it's value, why iterate over the whole array?
$user = 'user1';
$search = 'search1';
$replace = 'search4';
$array = array('user1' => 'search1', 'user2' => 'search2');
if (isset($array[$user]) && $search === $array[$user]) $array[$user] = $replace;
Similar to #Joseph's method (pretty much the same), but with a few tweaks:
$user = 'user1';
$array = array("user1" => "search1", "user2" => "search2" );
foreach($array as $key => &$value) {
if ($key === $user) {
$value = 'search4';
break; // Stop iterating after key has been found
}
}
Passing by reference is a nicer way to edit inside foreach, and is arguably quicker.
Search and replace inside an associative array or numeric
Replace value in any associative array and array can be any deep
function array_value_replace($maybe_array, $replace_from, $replace_to) {
if (!empty($maybe_array)) {
if (is_array($maybe_array)) {
foreach ($maybe_array as $key => $value) {
$maybe_array[$key] = array_value_replace($value, $replace_from, $replace_to);
}
} else {
if(is_string($maybe_array)){
$maybe_array = str_replace($replace_from, $replace_to, $maybe_array);
}
}
}
return $maybe_array;
}
if you want for particular key then you just add condition for key in previous ans like.
$user = "user1";
$myarray = array("user1" => "search1", "user2" => "search2" );
foreach($myarray as $key => $val)
{
if ($val == 'search1' && $key == $user) $myarray[$key] = 'search4';
}
Using str_replace should work:
$myarray = array("user1" => "search1", "user2" => "search2" ) ;
$newArray = str_replace('search1', 'search4', $myarray);
Following on from Joseph's answer, using preg_replace may enable you to use the code in other situations:
function pregReplaceInArray($pattern,$replacement,$array) {
foreach ($array as $key => $value) {
$array[$key] = preg_replace($pattern,$replacement,$value);
}
return $array;
}

How to merge arrays but no numerical keys in fewest lines in php?

$result = array_merge($arr1,$arr2);
I want to exclude numerical values of $arr2,is there an option for this?
Edit after comment:
$arr1 = array('key' => 1);
$arr2 = array('test',1 => 'test', 'key2' => 2);
after processing I need the result to be:
array('key' => 1,'key2' => 2);
Excluding numerical keys
It seems that you want to array_filter your $arr2's keys, first:
function not_numeric( $object ) {
return !is_numeric( $object );
}
$no_numeric_keys = array_filter( array_keys( $arr2 ), not_numeric );
$no_numeric_array = array_intersect_keys( $arr2, $no_numeric_keys );
$result = array_merge( $arr1, $no_numeric_array );
I'm guessing that this would work, after using $result = array_merge($arr1,$arr2);:
foreach ($result as $key => $value) {
if (is_numeric($key)) {
unset($result[$key]);
}
}
Edit:
In as few lines as possible (1) – as requested in the new title:
foreach ($result as $key => $value) { if (is_numeric($key)) { unset($result[$key]); } }
Just loop through each array and test if keys are strings:
$output = array();
foreach($arr1 as $key => $value) {
if(is_string($key)) {
$output[$key] = $value;
}
}
foreach($arr2 as $key => $value) {
if(is_string($key)) {
$output[$key] = $value;
}
}
Edit:
Since you said elegant...
function merge_arrays_string_keys()
{
$output = array();
foreach(func_get_args() as $arr)
{
if(is_array($arr))
{
foreach($arr as $key => $value) {
if(is_string($key) {
$output[$key] = $value;
}
}
}
}
return $output;
}
elegant, huh?
$test = array('test', 1 => 'test', 'key2' => 2, 33, 3 => 33, 'foo' => 'bar');
$test_non_num = array_intersect_key(
$test,
array_flip(
array_diff(
array_keys($test),
array_filter(array_keys($test), 'is_int'))));
print_r($test_non_num); // key2=>2, foo=>bar
Use this code , it will also do the require thing.
<?php
$result = array ( 1,"pavunkumar","bks", 123 , "3" ) ;
array_walk($result,'test_print');
print_r ( $result ) ;
function test_print( $val , $key )
{
global $result;
if ( gettype ( $val ) == 'integer' )
{
unset ( $result[$key] ) ;
}
}
array_diff_ukey($m=$arr2+$arr1,$m,function($k){return is_string($k);})

How to "flatten" a multi-dimensional array to simple one in PHP? [duplicate]

This question already has answers here:
How to Flatten a Multidimensional Array?
(31 answers)
Closed 1 year ago.
It's probably beginner question but I'm going through documentation for longer time already and I can't find any solution. I thought I could use implode for each dimension and then put those strings back together with str_split to make new simple array. However I never know if the join pattern isn't also in values and so after doing str_split my original values could break.
Is there something like combine($array1, $array2) for arrays inside of multi-dimensional array?
$array = your array
$result = call_user_func_array('array_merge', $array);
echo "<pre>";
print_r($result);
REF: http://php.net/manual/en/function.call-user-func-array.php
Here is another solution (works with multi-dimensional array) :
function array_flatten($array) {
$return = array();
foreach ($array as $key => $value) {
if (is_array($value)){ $return = array_merge($return, array_flatten($value));}
else {$return[$key] = $value;}
}
return $return;
}
$array = Your array
$result = array_flatten($array);
echo "<pre>";
print_r($result);
This is a one line, SUPER easy to use:
$result = array();
array_walk_recursive($original_array,function($v) use (&$result){ $result[] = $v; });
It is very easy to understand, inside the anonymous function/closure. $v is the value of your $original_array.
Use array_walk_recursive
<?php
$aNonFlat = array(
1,
2,
array(
3,
4,
5,
array(
6,
7
),
8,
9,
),
10,
11
);
$objTmp = (object) array('aFlat' => array());
array_walk_recursive($aNonFlat, create_function('&$v, $k, &$t', '$t->aFlat[] = $v;'), $objTmp);
var_dump($objTmp->aFlat);
/*
array(11) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(4)
[4]=>
int(5)
[5]=>
int(6)
[6]=>
int(7)
[7]=>
int(8)
[8]=>
int(9)
[9]=>
int(10)
[10]=>
int(11)
}
*/
?>
Tested with PHP 5.5.9-1ubuntu4.24 (cli) (built: Mar 16 2018 12:32:06)
If you specifically have an array of arrays that doesn't go further than one level deep (a use case I find common) you can get away with array_merge and the splat operator.
<?php
$notFlat = [[1,2],[3,4]];
$flat = array_merge(...$notFlat);
var_dump($flat);
Output:
array(4) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(4)
}
The splat operator effectively changes the array of arrays to a list of arrays as arguments for array_merge.
// $array = your multidimensional array
$flat_array = array();
foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $k=>$v){
$flat_array[$k] = $v;
}
Also documented:
http://www.phpro.org/examples/Flatten-Array.html
Sorry for necrobumping, but none of the provided answers did what I intuitively understood as "flattening a multidimensional array". Namely this case:
[
'a' => [
'b' => 'value',
]
]
all of the provided solutions would flatten it into just ['value'], but that loses information about the key and the depth, plus if you have another 'b' key somewhere else, it will overwrite them.
I wanted to get a result like this:
[
'a_b' => 'value',
]
array_walk_recursive doesn't pass the information about the key it's currently recursing, so I did it with just plain recursion:
function flatten($array, $prefix = '') {
$return = [];
foreach ($array as $key => $value) {
if (is_array($value)) {
$return = array_merge($return, flatten($value, $prefix . $key . '_'));
} else {
$return[$prefix . $key] = $value;
}
}
return $return;
}
Modify the $prefix and '_' separator to your liking.
Playground here: https://3v4l.org/0B8hf
With PHP 7, you can use generators and generator delegation (yield from) to flatten an array:
function array_flatten_iterator (array $array) {
foreach ($array as $value) {
if (is_array($value)) {
yield from array_flatten_iterator($value);
} else {
yield $value;
}
}
}
function array_flatten (array $array) {
return iterator_to_array(array_flatten_iterator($array), false);
}
Example:
$array = [
1,
2,
[
3,
4,
5,
[
6,
7
],
8,
9,
],
10,
11,
];
var_dump(array_flatten($array));
http://3v4l.org/RU30W
A non-recursive solution (but order-destroying):
function flatten($ar) {
$toflat = array($ar);
$res = array();
while (($r = array_shift($toflat)) !== NULL) {
foreach ($r as $v) {
if (is_array($v)) {
$toflat[] = $v;
} else {
$res[] = $v;
}
}
}
return $res;
}
function flatten_array($array, $preserve_keys = 0, &$out = array()) {
# Flatten a multidimensional array to one dimension, optionally preserving keys.
#
# $array - the array to flatten
# $preserve_keys - 0 (default) to not preserve keys, 1 to preserve string keys only, 2 to preserve all keys
# $out - internal use argument for recursion
foreach($array as $key => $child)
if(is_array($child))
$out = flatten_array($child, $preserve_keys, $out);
elseif($preserve_keys + is_string($key) > 1)
$out[$key] = $child;
else
$out[] = $child;
return $out;
}
Another method from PHP's user comments (simplified) and here:
function array_flatten_recursive($array) {
if (!$array) return false;
$flat = array();
$RII = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach ($RII as $value) $flat[] = $value;
return $flat;
}
The big benefit of this method is that it tracks the depth of the recursion, should you need that while flattening.
This will output:
$array = array(
'A' => array('B' => array( 1, 2, 3)),
'C' => array(4, 5)
);
print_r(array_flatten_recursive($array));
#Returns:
Array (
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
In PHP>=5.3 and based on Luc M's answer (the first one) you can make use of closures like this
array_walk_recursive($aNonFlat, function(&$v, $k, &$t){$t->aFlat[] = $v;}, $objTmp);
I love this because I don't have to surround the function's code with quotes like when using create_function()
Using higher-order functions (note: I'm using inline anonymous functions, which appeared in PHP 5.3):
function array_flatten($array) {
return array_reduce(
$array,
function($prev, $element) {
if (!is_array($element))
$prev[] = $element;
else
$prev = array_merge($prev, array_flatten($element));
return $prev;
},
array()
);
}
I found a simple way to convert multilevel array into one.
I use the function "http_build_query" which converts the array into a url string.
Then, split the string with explode and decode the value.
Here is a sample.
$converted = http_build_query($data);
$rows = explode('&', $converted);
$output = array();
foreach($rows AS $k => $v){
list($kk, $vv) = explode('=', $v);
$output[ urldecode($kk) ] = urldecode($vv);
}
return $output;
A new approach based on the previous example function submited by chaos, which fixes the bug of overwritting string keys in multiarrays:
# Flatten a multidimensional array to one dimension, optionally preserving keys.
# $array - the array to flatten
# $preserve_keys - 0 (default) to not preserve keys, 1 to preserve string keys only, 2 to preserve all keys
# $out - internal use argument for recursion
function flatten_array($array, $preserve_keys = 2, &$out = array(), &$last_subarray_found)
{
foreach($array as $key => $child)
{
if(is_array($child))
{
$last_subarray_found = $key;
$out = flatten_array($child, $preserve_keys, $out, $last_subarray_found);
}
elseif($preserve_keys + is_string($key) > 1)
{
if ($last_subarray_found)
{
$sfinal_key_value = $last_subarray_found . "_" . $key;
}
else
{
$sfinal_key_value = $key;
}
$out[$sfinal_key_value] = $child;
}
else
{
$out[] = $child;
}
}
return $out;
}
Example:
$newarraytest = array();
$last_subarray_found = "";
$this->flatten_array($array, 2, $newarraytest, $last_subarray_found);
/*consider $mArray as multidimensional array and $sArray as single dimensional array
this code will ignore the parent array
*/
function flatten_array2($mArray) {
$sArray = array();
foreach ($mArray as $row) {
if ( !(is_array($row)) ) {
if($sArray[] = $row){
}
} else {
$sArray = array_merge($sArray,flatten_array2($row));
}
}
return $sArray;
}
you can try this:
function flat_an_array($a)
{
foreach($a as $i)
{
if(is_array($i))
{
if($na) $na = array_merge($na,flat_an_array($i));
else $na = flat_an_array($i);
}
else $na[] = $i;
}
return $na;
}
If you're okay with loosing array keys, you may flatten a multi-dimensional array using a recursive closure as a callback that utilizes array_values(), making sure that this callback is a parameter for array_walk(), as follows.
<?php
$array = [1,2,3,[5,6,7]];
$nu_array = null;
$callback = function ( $item ) use(&$callback, &$nu_array) {
if (!is_array($item)) {
$nu_array[] = $item;
}
else
if ( is_array( $item ) ) {
foreach( array_values($item) as $v) {
if ( !(is_array($v))) {
$nu_array[] = $v;
}
else
{
$callback( $v );
continue;
}
}
}
};
array_walk($array, $callback);
print_r($nu_array);
The one drawback of the preceding example is that it involves writing far more code than the following solution which uses array_walk_recursive() along with a simplified callback:
<?php
$array = [1,2,3,[5,6,7]];
$nu_array = [];
array_walk_recursive($array, function ( $item ) use(&$nu_array )
{
$nu_array[] = $item;
}
);
print_r($nu_array);
See live code
This example seems preferable to the previous one, hiding the details about how values are extracted from a multidimensional array. Surely, iteration occurs, but whether it entails recursion or control structure(s), you'll only know from perusing array.c. Since functional programming focuses on input and output rather than the minutiae of obtaining a result, surely one can remain unconcerned about how behind-the-scenes iteration occurs, that is until a perspective employer poses such a question.
You can use the flatten function from Non-standard PHP library (NSPL). It works with arrays and any iterable data structures.
assert([1, 2, 3, 4, 5, 6, 7, 8, 9] === flatten([[1, [2, [3]]], [[[4, 5, 6]]], 7, 8, [9]]));
Simple approach..See it via recursion..
<?php
function flatten_array($simple){
static $outputs=array();
foreach ( $simple as $value)
{
if(is_array($value)){
flatten_array($value);
}
else{
$outputs[]=$value;
}
}
return $outputs;
}
$eg=['s'=>['p','n'=>['t']]];
$out=flatten_array($eg);
print_r($out);
?>
Someone might find this useful, I had a problem flattening array at some dimension, I would call it last dimension so for example, if I have array like:
array (
'germany' =>
array (
'cars' =>
array (
'bmw' =>
array (
0 => 'm4',
1 => 'x3',
2 => 'x8',
),
),
),
'france' =>
array (
'cars' =>
array (
'peugeot' =>
array (
0 => '206',
1 => '3008',
2 => '5008',
),
),
),
)
Or:
array (
'earth' =>
array (
'germany' =>
array (
'cars' =>
array (
'bmw' =>
array (
0 => 'm4',
1 => 'x3',
2 => 'x8',
),
),
),
),
'mars' =>
array (
'france' =>
array (
'cars' =>
array (
'peugeot' =>
array (
0 => '206',
1 => '3008',
2 => '5008',
),
),
),
),
)
For both of these arrays when I call method below I get result:
array (
0 =>
array (
0 => 'm4',
1 => 'x3',
2 => 'x8',
),
1 =>
array (
0 => '206',
1 => '3008',
2 => '5008',
),
)
So I am flattening to last array dimension which should stay the same, method below could be refactored to actually stop at any kind of level:
function flattenAggregatedArray($aggregatedArray) {
$final = $lvls = [];
$counter = 1;
$lvls[$counter] = $aggregatedArray;
$elem = current($aggregatedArray);
while ($elem){
while(is_array($elem)){
$counter++;
$lvls[$counter] = $elem;
$elem = current($elem);
}
$final[] = $lvls[$counter];
$elem = next($lvls[--$counter]);
while ( $elem == null){
if (isset($lvls[$counter-1])){
$elem = next($lvls[--$counter]);
}
else{
return $final;
}
}
}
}
If you're interested in just the values for one particular key, you might find this approach useful:
function valuelist($array, $array_column) {
$return = array();
foreach($array AS $row){
$return[]=$row[$array_column];
};
return $return;
};
Example:
Given $get_role_action=
array(3) {
[0]=>
array(2) {
["ACTION_CD"]=>
string(12) "ADD_DOCUMENT"
["ACTION_REASON"]=>
NULL
}
[1]=>
array(2) {
["ACTION_CD"]=>
string(13) "LINK_DOCUMENT"
["ACTION_REASON"]=>
NULL
}
[2]=>
array(2) {
["ACTION_CD"]=>
string(15) "UNLINK_DOCUMENT"
["ACTION_REASON"]=>
NULL
}
}
than $variables['role_action_list']=valuelist($get_role_action, 'ACTION_CD'); would result in:
$variables["role_action_list"]=>
array(3) {
[0]=>
string(12) "ADD_DOCUMENT"
[1]=>
string(13) "LINK_DOCUMENT"
[2]=>
string(15) "UNLINK_DOCUMENT"
}
From there you can perform value look-ups like so:
if( in_array('ADD_DOCUMENT', $variables['role_action_list']) ){
//do something
};
any of this didnt work for me ...
so had to run it myself.
works just fine:
function arrayFlat($arr){
$out = '';
foreach($arr as $key => $value){
if(!is_array($value)){
$out .= $value.',';
}else{
$out .= $key.',';
$out .= arrayFlat($value);
}
}
return trim($out,',');
}
$result = explode(',',arrayFlat($yourArray));
echo '<pre>';
print_r($result);
echo '</pre>';
Given multi-dimensional array and converting it into one-dimensional, can be done by unsetting all values which are having arrays and saving them into first dimension, for example:
function _flatten_array($arr) {
while ($arr) {
list($key, $value) = each($arr);
is_array($value) ? $arr = $value : $out[$key] = $value;
unset($arr[$key]);
}
return (array)$out;
}

Categories