loop through multidimensional array php - get all index and implode to string - php

I am stuck with a part of my code and i can't see to figure out why i get a certain result. What my goal is to loop through the array and echo this result as a string:
First Array
validate.required
validate.remote
Second array
shop.cart.string
Current result is:
validate.0.required
validate.1.remote
It returns the index from the array, how can solve this/remove this from my string?
private $translationKeys = [
'validate' => [
'required',
'remote',
'email',
'url',
'date',
'dateISO',
'number',
'digits',
'creditcard',
'equalTo',
'extension',
'maxlength',
'minlength',
'rangelength',
'range',
'max',
'min',
'step'
],
'shop' => [
'cart' => [
'string'
],
],
];
​
This is my function:
function listArrayRecursive($translationKeys) {
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($translationKeys), RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $k => $v) {
if ($iterator->hasChildren()) {
} else {
for ($p = array(), $i = 0, $z = $iterator->getDepth(); $i <= $z; $i++) {
$p[] = $iterator->getSubIterator($i)->key();
$y = array();
foreach ($p as $value) {
array_push($y, $value);
}
}
$path = implode('.', $y);
$a[] = "$path.$v<br>";
// Here i want to echo the string
}
}
}
Second version of the function
function listArrayRecursive($translationKeys) {
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($translationKeys), RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $k => $v) {
if ($iterator->hasChildren()) {
} else {
for ($p = array(), $i = 0, $z = $iterator->getDepth(); $i <= $z; $i++) {
$p[] = $iterator->getSubIterator($i)->key();
}
$path = implode('.', $p);
$a[] = "$path.$v<br>";
}
}
}

Here's a function that will give you the result you desire. It recurses through each element of the array that is an array, concatenating the key with the values, or just returns the value if it is not an array:
function listArrayRecursive($array) {
$list = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
foreach (listArrayRecursive($value) as $v) {
$list[] = "$key.$v";
}
}
else {
$list[] = $value;
}
}
return $list;
}
print_r(listArrayRecursive($translationKeys));
Output:
Array (
[0] => validate.required
[1] => validate.remote
[2] => validate.email
[3] => validate.url
[4] => validate.date
[5] => validate.dateISO
[6] => validate.number
[7] => validate.digits
[8] => validate.creditcard
[9] => validate.equalTo
[10] => validate.extension
[11] => validate.maxlength
[12] => validate.minlength
[13] => validate.rangelength
[14] => validate.range
[15] => validate.max
[16] => validate.min
[17] => validate.step
[18] => shop.cart.string
)
Demo on 3v4l.org

try something like this
function disp_array_rec($arr, $upper = null) {
foreach ($arr as $k => $v) {
echo ($upper != null ? $upper : "");
if (is_array($v)) {
disp_array_rec($v, $k . ".");
} else {
echo "$v\n";
}
}
}
disp_array_rec($translationKeys);
result:
validate.required
validate.remote
validate.email
validate.url
validate.date
validate.dateISO
validate.number
validate.digits
validate.creditcard
validate.equalTo
validate.extension
validate.maxlength
validate.minlength
validate.rangelength
validate.range
validate.max
validate.min
validate.step
shop.cart.string

Related

How can I convert `$arr['something1']['something2'] = value;` into `$arr['something1[something2]'] = value` in PHP?

I am stuck...
I have this value in my PHP:
$arr['something1']['something2'] = value;
I want to have a func($arr) that returns:
$arr['something1[something2]'] = value;
Here is my current codes for nested 3 arrays:
static function flattenArray(array $notFlat, string $pK) {
$index = 0;
foreach ($notFlat as $k => $v) {
if (is_array($v)) {
foreach ($v as $_k => $_v) {
if (is_array($_v)) {
foreach ($_v as $__k => $__v) {
if (is_array($__v)) {}
else{
unset($notFlat[$k]);
$newArray = array_slice($notFlat, 0, $index, true) +
$notFlat[$k] = [$pK.$k.'['.$_k.']'.'['.$__k.']' => $__v] +
array_slice($notFlat, $index, NULL, true);
$notFlat = $newArray;
}
}
}
}
}
$index ++;
}
return $notFlat;
}
But that is too manual... I think recursive function can work but I am not sure what to return in case iterated value is an array.
EDIT1: Expected Output
$asd = ['asd' => ['jkf' => ['qwe' => 'wer', 'asd' => '123', 'kjk' => 'sdf', '456' => 'zxc']], 'dfg', 'test' => ['ert' => '234'], 'cvf'];
print_r(func($asd));
/*
Array
(
[test[ert]] => 234
[asd[jkf][456]] => zxc
[asd[jkf][kjk]] => sdf
[asd[jkf][asd]] => 123
[asd[jkf][qwe]] => wer
[0] => dfg
[1] => cvf
)
*/
function flattenArray(array $notFlat) {
function _flattenArray(&$arrayRoot, $arrayCurr, $kS) {
foreach ($arrayCurr as $k => $v) {
if (is_array($v)) {
_flattenArray($arrayRoot, $v, $kS.'['.$k.']');
}
else {
$currentKey = (string) $kS.'['.$k.']';
$arrayRoot[$currentKey] = $v;
}
}
}
foreach ($notFlat as $k => $v) {
if (is_array($v)) {
_flattenArray($notFlat, $v, $k);
unset($notFlat[$k]);
}
}
return $notFlat;
}
Code ( https://3v4l.org/5LVii )
$asd = ['asd' => ['jkf' => ['qwe' => 'wer', 'asd' => '123', 'kjk' => 'sdf', '456' => 'zxc']], 'dfg', 'test' => ['ert' => '234'], 'cvf'];
function recurse($array,$key=''){
static $output=[];
foreach($array as $k=>$v){
if(is_array($v)){
recurse($v,$key?$key.'['.$k.']':$k);
}else{
$output[$key?$key.'['.$k.']':$k]=$v;
}
}
return $output;
}
var_export(recurse($asd));
Output:
array (
'asd[jkf][qwe]' => 'wer',
'asd[jkf][asd]' => '123',
'asd[jkf][kjk]' => 'sdf',
'asd[jkf][456]' => 'zxc',
0 => 'dfg',
'test[ert]' => '234',
1 => 'cvf',
)
There isn't much that I can explain. The snippet iterates and recurses the array, appending the keys as it recurses. static allows the reuse/build of $output.

Compare multidimensional array with simple array

I have two arrays I want to compare these two arrays and find the match. If 807 and 200 appears in same keys like 131 then create third array
array(131=>(807,200));
array1:-
Array([0] => 807,[1] => 200)
array2 :-
$mat= Array([0] => Array([131] => 807),[1] => Array([132] => 807),[2] => Array([125] => 200),[3] => Array([131] => 200))
My code:
<?php
$filtered = array();
array_walk_recursive($matchingskusarr, function($val, $key) use(&$filtered) {
if ($key === 131) {
echo "The key $key has the value $val<br>";
$filtered[$val] = $key;
}
});
echo "<pre>";
print_r($filtered);
echo "</pre>";
?>
You can use array_column like this:
$filtered = array_column($mat, 131);
//Output: Array ( [0] => 807 [1] => 200 )
Update 1:
$matchingskusarr = Array( 0 => Array(131 => 807), 1 => Array(132 => 807),2 => Array(125 => 200),3 => Array(131 => 200)) ;
$skus = array(0=>807, 1=>200);
function yourMatch($skus, $matchingskusarr) {
$continue = [];
foreach ($matchingskusarr as $array) {
//Get the first key !!!
foreach ($array as $key => $value);
//Column already tested just continue
if(isset($continue[$key])) {
continue;
}
//New column we need to check if it matches our $skus
$column = array_column($matchingskusarr, $key);
if($column == $skus) {
return [$key => $column ];
}
$continue[$key] = true;
}
return null;
}
print_r(yourMatch($skus, $matchingskusarr));
Demo: https://3v4l.org/Cr2L4

Search in a multidimensional assoc array

I have an array, looking like this:
[lund] => Array
(
[69] => foo
)
[berlin] => Array
(
[138] => foox2
)
[tokyo] => Array
(
[180] => foox2
[109] => Big entrance
[73] => foo
)
The thing is that there were duplicate keys, so I re-arranged them so I can search more specifically, I thought.
Previously I could just
$key = array_search('foo', $array);
to get the key but now I don't know how.
Question: I need key for value foo, from tokyo. How do I do that?
You can get all keys and value of foo by using this:
foreach ($array as $key => $value) {
$newArr[$key] = array_search('foo', $value);
}
print_r(array_filter($newArr));
Result is:
Array
(
[lund] => 69
[tokyo] => 109
)
If you don't mind about the hard code than you can use this:
array_search('foo', $array['tokyo']);
It just a simple example, you can modify it as per your requirement.
Try this
$a = array(
"land"=> array("69"=>"foo"),
"land1"=> array("138"=>"foo1"),
"land2"=> array('180' => 'foox2',
'109' => 'Big entrance',
'73' => 'foo'),
);
//print_r($a);
$reply = search_in_array($a, "foo");
print_r($reply);
function search_in_array($a, $search)
{
$result = array();
foreach($a as $key1 => $array ) {
foreach($array as $k => $value) {
if($value == "$search") {
array_push($result,"{$key1}=>{$k}");
breck;
}
}
}
return $result;
}
This function will return the key or null if the search value is not found.
function search($searchKey, $searchValue, $searchArr)
{
foreach ($searchArr as $key => $value) {
if ($key == $searchKey && in_array($searchValue, $value)) {
$results = array_search($searchValue, $value);
}
}
return isset($results) ? $results : null;
}
// var_dump(search('tokyo', 'foo', $array));
Since Question: I need key for value foo, from tokyo. How do i do that?
$key = array_search('foo', $array['tokyo']);
As a function:
function getKey($keyword, $city, $array) {
return array_search($keyword, $array[$city]);
}
// PS. Might be a good idea to wrap this array in an object and make getKey an object method.
If you want to get all cities (for example to loop through them):
$cities = array_keys($array);
I created solution using array iterator. Have a look on below solution:
$array = array(
'lund' => array
(
'69' => 'foo'
),
'berlin' => array
(
'138' => 'foox2'
),
'tokyo' => array
(
'180' => 'foox2',
'109' => 'Big entrance',
'73' => 'foo'
)
);
$main_key = 'tokyo'; //key of array
$search_value = 'foo'; //value which need to be search
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach ($iterator as $key => $value) {
$keys = array();
if ($value == $search_value) {
$keys[] = $key;
for ($i = $iterator->getDepth() - 1; $i >= 0; $i--) {
$keys[] = $iterator->getSubIterator($i)->key();
}
$key_paths = array_reverse($keys);
if(in_array($main_key, $key_paths) !== false) {
echo "'{$key}' have '{$value}' value which traverse path is: " . implode(' -> ', $key_paths) . '<br>';
}
}
}
you can change value of $main_key and $serch_value according to your parameter. hope this will help you.
<?php
$lund = [
'69' => 'foo'
];
$berlin = [
'138' => 'foox2'
];
$tokyo = [
'180' => 'foox2',
'109' => 'Big entrance',
'73' => 'foo'
];
$array = [
$lund,
$berlin,
$tokyo
];
echo $array[2]['180']; // outputs 'foox2' from $tokyo array
?>
If you want to get key by specific key and value then your code should be:
function search_array($array, $key, $value)
{
if(is_array($array[$key])) {
return array_search($value, $array[$key]);
}
}
echo search_array($arr, 'tokyo', 'foo');
try this:
<?php
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 'On');
$array=array("lund" => array
(
69 => "foo"
),
"berlin" => array
(
138 => "foox2"
),
"tokyo" => array
(
180 => "foox2",
109 => "Big entrance",
73 => "foo"
));
function search($array, $arrkey1, $arrvalue2){
foreach($array as $arrkey=>$arrvalue){
if($arrkey == $arrkey1){
foreach($arrvalue as $arrkey=>$arrvalue){
if(preg_match("/$arrvalue/i",$arrvalue2))
return $arrkey;
}
}
}
}
$result=search($array, "tokyo", "foo"); //$array=array; tokyo="inside array to check"; foo="value" to check
echo $result;
You need to loop through array, since its 2 dimensional in this case. And then find corresponding value.
foreach($arr as $key1 => $key2 ) {
foreach($key2 as $k => $value) {
if($value == "foo") {
echo "{$k} => {$value}";
}
}
}
This example match key with $value, but you can do match with $k also, which in this case is $key2.

How to extract array Keys to String in an array PHP

I need to extract a associative array keys into a string and implode with "/" or any character/symbols.
For eg:
$array = array([key1] =>
array([key11] =>
array([key111] => 'value111',
[key112] => 'value112',
[key113] => 'value113',
),
),
);
I need an output as below array:
array([0] => 'key1/key11/key111',[1] => 'key1/key11/key112', [2] => 'key1/key11/key112');
I've edited an answer given here and came up with the following code.
function listArrayRecursive($someArray, &$outputArray, $separator = "/") {
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($someArray), RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $k => $v) {
if (!$iterator->hasChildren()) {
for ($p = array(), $i = 0, $z = $iterator->getDepth(); $i <= $z; $i++) {
$p[] = $iterator->getSubIterator($i)->key();
}
$path = implode($separator, $p);
$outputArray[] = $path;
}
}
}
$outputArray = array();
listArrayRecursive($array, $outputArray);
print_r($outputArray);
Input:
Array
(
[key1] => Array
(
[key11] => Array
(
[key111] => value111
[key112] => value113
[key113] => value113
)
)
)
Output:
Array
(
[0] => key1/key11/key111
[1] => key1/key11/key112
[2] => key1/key11/key113
)
Works for different depth of array:
function getKeys($array, $prefix='', $separator = '/') {
$return = array();
foreach($array as $key => $value) {
if (!is_array($value)) $return[] = $prefix . $key;
else $return = array_merge($return, getKeys($value, $prefix . $key . separator), $separator);
}
return $return;
}
$keys = getKeys($array, '', '#');
See online fiddle http://ideone.com/krU4Xn
you could do something like...
$mapArray = array();
$symbol = '/';
foreach($array as $k =>$v)
foreach($v as $k1 =>$v1)
foreach($v1 as $k2 =>$v2)
$mapArray[] = $k.$symbol.$k1.$symbol.$k2;
also this obviously only works in this particular case, if it needs to be more generic it can be done, but I think this should get you started.

Get array's key recursively and create underscore separated string

Right now i got an array which has some sort of information and i need to create a table from it. e.g.
Student{
[Address]{
[StreetAddress] =>"Some Street"
[StreetName] => "Some Name"
}
[Marks1] => 100
[Marks2] => 50
}
Now I want to create database table like which contain the fields name as :
Student_Address_StreetAddress
Student_Address_StreetName
Student_Marks1
Student_Marks2
It should be recursive so from any depth of array it can create the string in my format.
You can use the RecursiveArrayIterator and the RecursiveIteratorIterator (to iterate over the array recursively) from the Standard PHP Library (SPL) to make this job relatively painless.
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
$keys = array();
foreach ($iterator as $key => $value) {
// Build long key name based on parent keys
for ($i = $iterator->getDepth() - 1; $i >= 0; $i--) {
$key = $iterator->getSubIterator($i)->key() . '_' . $key;
}
$keys[] = $key;
}
var_export($keys);
The above example outputs something like:
array (
0 => 'Student_Address_StreetAddress',
1 => 'Student_Address_StreetName',
2 => 'Student_Marks1',
3 => 'Student_Marks2',
)
(Working on it, here is the array to save the trouble):
$arr = array
(
'Student' => array
(
'Address' => array
(
'StreetAddress' => 'Some Street',
'StreetName' => 'Some Name',
),
'Marks1' => '100',
'Marks2' => '50',
),
);
Here it is, using a modified version of #polygenelubricants code:
function dfs($array, $parent = null)
{
static $result = array();
if (is_array($array) * count($array) > 0)
{
foreach ($array as $key => $value)
{
dfs($value, $parent . '_' . $key);
}
}
else
{
$result[] = ltrim($parent, '_');
}
return $result;
}
echo '<pre>';
print_r(dfs($arr));
echo '</pre>';
Outputs:
Array
(
[0] => Student_Address_StreetAddress
[1] => Student_Address_StreetName
[2] => Student_Marks1
[3] => Student_Marks2
)
Something like this maybe?
$schema = array(
'Student' => array(
'Address' => array(
'StreetAddresss' => "Some Street",
'StreetName' => "Some Name",
),
'Marks1' => 100,
'Marks2' => 50,
),
);
$result = array();
function walk($value, $key, $memo = "") {
global $result;
if(is_array($value)) {
$memo .= $key . '_';
array_walk($value, 'walk', $memo);
} else {
$result[] = $memo . $key;
}
}
array_walk($schema, 'walk');
var_dump($result);
I know globals are bad, but can't think of anything better now.
Something like this works:
<?php
$arr = array (
'Student' => array (
'Address' => array (
'StreetAddress' => 'Some Street',
'StreetName' => 'Some Name',
),
'Marks1' => array(),
'Marks2' => '50',
),
);
$result = array();
function dfs($data, $prefix = "") {
global $result;
if (is_array($data) && !empty($data)) {
foreach ($data as $key => $value) {
dfs($value, "{$prefix}_{$key}");
}
} else {
$result[substr($prefix, 1)] = $data;
}
}
dfs($arr);
var_dump($result);
?>
This prints:
array(4) {
["Student_Address_StreetAddress"] => string(11) "Some Street"
["Student_Address_StreetName"] => string(9) "Some Name"
["Student_Marks1"] => array(0) {}
["Student_Marks2"] => string(2) "50"
}
function getValues($dataArray,$strKey="")
{
global $arrFinalValues;
if(is_array($dataArray))
{
$currentKey = $strKey;
foreach($dataArray as $key => $val)
{
if(is_array($val) && !empty($val))
{
getValues($val,$currentKey.$key."_");
}
else if(!empty($val))
{
if(!empty($strKey))
$strTmpKey = $strKey.$key;
else
$strTmpKey = $key;
$arrFinalValues[$strTmpKey]=$val;
}
}
}
}

Categories