Get Array's Key Recursively and Create Underscore Separated String

Flatten multidimensional array concatenating keys

Thanks for all the given answers.

I have transformed it in the following, which is an improved version. It eliminates the need of a root prefix, does not need to use references, it is cleaner to read, and it has a better name:

function array_flat($array, $prefix = '')
{
$result = array();

foreach ($array as $key => $value)
{
$new_key = $prefix . (empty($prefix) ? '' : '.') . $key;

if (is_array($value))
{
$result = array_merge($result, array_flat($value, $new_key));
}
else
{
$result[$new_key] = $value;
}
}

return $result;
}

Convert array keys from underscore_case to camelCase recursively

The recursive part cannot be further simplified or prettified.

But the conversion from underscore_case (also known as snake_case) and camelCase can be done in several different ways:

$key = 'snake_case_key';
// split into words, uppercase their first letter, join them,
// lowercase the very first letter of the name
$key = lcfirst(implode('', array_map('ucfirst', explode('_', $key))));

or

$key = 'snake_case_key';
// replace underscores with spaces, uppercase first letter of all words,
// join them, lowercase the very first letter of the name
$key = lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $key))));

or

$key = 'snake_case_key':
// match underscores and the first letter after each of them,
// replace the matched string with the uppercase version of the letter
$key = preg_replace_callback(
'/_([^_])/',
function (array $m) {
return ucfirst($m[1]);
},
$key
);

Pick your favorite!

Convert all recursive keys to underscore_with lower_case in java

In java 9 you can try using this:

String newJsonString = Pattern.compile("[A-Z](?=(\\w*)\":)")
.matcher(jsonString)
.replaceAll(matchResult -> "_" + matchResult.group().toLowerCase());

For lower version you can try this:

    Pattern p = Pattern.compile("[A-Z](?=\\w*\":)");
Matcher m = p.matcher(jsonString);

StringBuffer sb = new StringBuffer();
while(m.find()){
String match = m.group();
m.appendReplacement(sb, "_" + match.toLowerCase());
}
m.appendTail(sb);
String newJsonString = sb.toString();

Addition:
To turn it back again from snake case to camel case you can use the same code, but use

Pattern p = Pattern.compile("_[a-z](?=\\w*\":)");

and

m.appendReplacement(sb, match.substring(1).toUpperCase());

instead

Make a PHP array display nicely

Okay I've put together the most rudimentary foreach loop thee world has seen, and yes I hate myself for it, but just in case anyone wants a dirty way to do this:

foreach($response['data'] as $r){
echo $r['name'] . "<br>";
foreach($r['children'] as $child){
echo $r['name'] . " | " . $child['name'] . "<br>";
foreach($child['children'] as $a){
echo $r['name'] . " | " . $child['name'] . " | " . $a['name'] . "<br>";
foreach($a['children'] as $b){
echo $r['name'] . " | " . $child['name'] . " | " . $a['name'] . " | " . $b['name'] . "<br>";
foreach($b['children'] as $c){
echo $r['name'] . " | " . $child['name'] . " | " . $a['name'] . " | " . $b['name'] . " | " . $c['name'] . "<br>";
foreach($c['children'] as $d){
echo $r['name'] . " | " . $child['name'] . " | " . $a['name'] . " | " . $b['name'] . " | " . $c['name'] . " | " . $d['name'] . "<br>";
}
}
}
}
}
}

Bare in mind you have to create a foreach for the max number of sub arrays

Output:

Accessories
Accessories | Chokers
Accessories | Garters
Accessories | Gloves
Accessories | Masks
Accessories | Nipple Covers
Accessories | Pride
Accessories | Pride | Confetti

PHP convert deep array

As simple as

$array = array(
'a' => array(
'b' => array(
'c' => 'val'
),
'd' => 'val2'
),
'e' => 'val3'
);

var_dump(collapse($array));

function collapse($array)
{
$result = array();
foreach ($array as $key => $val) {
if (is_array($val)) {
foreach (collapse($val) as $nested_key => $nested_val) {
$result[$key . '.' . $nested_key] = $nested_val;
}
} else {
$result[$key] = $val;
}
}

return $result;
}

http://ideone.com/ieSZ6

PS: usually I don't like to give complete solutions, but in this case - the solution might be too difficult for newbie

Filling an array recursively

This is tricky, but with the use of reference you can do it iteratively (or recursively if you set up a function)

The key here is to use $cur = &$cur[$v]; to nest new keys

$path = explode('_', substr($value['path'], strlen($key . '_')));
$array = array();

// Start nesting new keys
$cur = &$array;
foreach($path as $v){
$cur[$v] = array();
$cur = &$cur[$v];
}

// Final assignnemnt
$cur = $value['value'];

Live on ideone: http://ideone.com/VtKqlD

Php multidimensional array to simple array

<?php
$array = array(
'one' => 'one_value',
'two' => array
(
'four' => 'four_value',
'five' => 'five_value'
),

'three' => array
(
'six' => array
(
'seven' => 'seven_value'
)

)
);

function flatten($array, $prefix = '') {
$arr = array();
foreach($array as $k => $v) {
if(is_array($v)) {
$arr = array_merge($arr, flatten($v, $prefix . $k . '-'));
}
else{
$arr[$prefix . $k] = $v;
}
}
return $arr;
}

var_dump(flatten($array));

//output:
//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"
//}

Running example

Recursively convert to false in object using underscore

If you want to modify your objects, you have to go ahead and do it!

function z(object){ 
_.each(object, function(value, key){
if(_.isObject(value)){
z(value);
}else{
object[key] = (value === "") ? false : value;
}
});
}

That modifies your object directly, not creating a new object.

The problem with _.map() is that it always returns an array. If you want to end up with an object, like the original, you can't use it.



Related Topics



Leave a reply



Submit