Make my array pretty - php

I have an array wich is structured like this
foo = stuff we don't care for this example
foo1_value
foo1_label
foo1_unit
foo2_value
foo3_label
foo3_value
Can you figure out a fast way to make it look like that ?
foo
foo1
value
label
unit
foo2
value
foo3
value
label
I'm actually trying with something like this :
array_walk($array, function($val, $key) use(&$nice_array) {
$match = false;
preg_match("/_label|_value|_unit|_libelle/", $key, $match);
if (count($match)) {
list($name, $subName) = explode('_', $key);
$nice_array[$name][$subName] = $val;
} else {
$nice_array[$key] = $val;
}
});
echo '<pre>';
print_r($nice_array);
echo '</pre>';
This is working I'll just have to reflect on the foo_foo_label thing and it's all good

You could use explode on the array keys, something like this:
$newArray = array();
foreach ( $array as $key => $value )
{
$parts = explode('_', $key);
$newArray[$parts[0]][$parts[1]] = $value;
}
Edit: update as detailed in comments. Will handle your foo_foo_value case as well as foo and foo_foo. There's really no reason to use array_walk if you're only passing the results off to a second array.
$newArray = array();
foreach ( $array as $key => $value ) {
if ( preg_match('/_(label|value|unit)$/', $key) === 0 ) {
$newArray[$key] = $value;
continue;
}
$pos = strrpos($key, '_');
$newArray[substr($key, 0, $pos)][substr($key, $pos+1, strlen($key))] = $value;
}

What you can do is loop over the array, and split (explode()) each key on _ to build your new array.
$newArray = array();
foreach($oldArray as $key=>$value){
list($name, $subName) = explode('_', $key);
if($subName !== NULL){
if(!isset($newArray[$name])){
$newArray[$name] = array();
}
$newArray[$name][$subName] = $value;
}
else{
$newArray[$name] = $value;
}
}

$nice_array = array();
array_walk($array, function($val, $key) use(&$nice_array) {
$match = false;
preg_match("/_label|_value|_unit|_libelle/", $key, $match);
if (count($match)) {
$tname = preg_split("/_label$|_value$|_unit$|_libelle$/",$key);
$name = $tname[0];
$subName = substr($match[0],1);
$nice_array[$name][$subName] = $val;
} else {
$nice_array[$key] = $val;
}
});

Related

Is it possible for a variable to evaluate to a multi-dimensional PHP array index

Given a multidimensional array or dictionary $array.
And assuming that $array['foo']['bar']['baz'] = 'something';
Is there a way other than via an eval statement for me use the multi-dimentional index foo/bar/baz? (The use case is in creating the index dynamically i.e. The function does not know what /foo/bar/baz/ is).
The only way I could figure to do this was:
$item = testGetIndex($array, "'foo']['bar']['baz'");
function testGetIndex($array, $index) {
eval('$item = $array[' . $index . '];');
return $item;
}
Note:
I should mention that I do not want to search this array. This is a weird use case. I am being passed a very large multi dimensional array and it's ugly to have to use constructs like..
$array[foo][bar]..[baz] to make modifications to the array.
Blatently reusing my answer here:
function recurseKeys(array $keys,array $array){
$key = array_shift($keys);
if(!isset($array[$key])) return null;
return empty($keys) ?
$array[$key]:
recurseKeys($keys,$array[$key];
}
$values = recurseKeys(explode('/','foo/bar/baz'),$yourArray);
edit: as Jack pointed out, recursion is not needed:
function findByKey(array $keys,array $array){
while(!is_null($key = array_shift($keys))){
if(!isset($array[$key])) return null;
$array = $array[$key];
}
return $array;
}
$values = findByKey(explode('/','foo/bar/baz'),$yourArray);
To modify an array using a path:
function setPath(&$root, $path, $value)
{
$paths = explode('/', $path);
$current = &$root;
foreach ($paths as $path) {
if (isset($current[$path])) {
$current = &$current[$path];
} else {
return null;
}
}
return $current = $value;
}
$path = 'foo/bar/baz';
$root = array('foo' => array('bar' => array('baz' => 'something')));
setPath($root, $path, '123');
You can tweak the function to just return a reference to the element you wish to change:
function &getPath(&$root, $path)
{
$paths = explode('/', $path);
$current = &$root;
foreach ($paths as $path) {
if (isset($current[$path])) {
$current = &$current[$path];
} else {
return null;
}
}
return $current;
}
$x = &getPath($root, $path);
$x = 456; // $root['foo']['bar']['baz'] == 456
A simple loop can make it, like:
function get(array $array, $keys) {
$val = $array;
foreach (explode('/', $keys) as $part) {
if (!isset($val[$part])) {
return null;
}
$val = $val[$part];
}
return $val;
}
$array['foo']['bar']['baz'] = 'something';
echo get($array, 'foo/bar/baz');
http://ideone.com/vcRvXW
Edit:
For modification, just use references:
function set(array &$array, $keys, $value) {
$val = &$array;
foreach (explode('/', $keys) as $part) {
if (!isset($val[$part])) {
$val[$part] = array();
}
$val = &$val[$part];
}
$val = $value;
}
http://ideone.com/WUNhF6

Comparing in_array values

I have a array of val which has dynamic strings with underscores. Plus I have a variable $key which contains an integer. I need to match $key with each $val (values before underscore).
I did the following way:
<?php
$key = 2; //always a dynamic number
$val = array('3_33', '2_55'); //always a dynamic string with underscore
if(in_array($key, $val)) {
echo 'Yes';
}
else
{
echo 'No';
}
?>
Though this code works fine, I want to know if its a correct way or suggest some better alternative.
use this function for regex match from php.net
function in_array_match($regex, $array) {
if (!is_array($array))
trigger_error('Argument 2 must be array');
foreach ($array as $v) {
$match = preg_match($regex, $v);
if ($match === 1) {
return true;
}
}
return false;
}
and then change your code to use this function like this:
$key = 2; //always a dynamic number
$val = array('3_33', '2_55'); //always a dynamic string with underscore
if(in_array_match($key."_*", $val)) {
echo 'Yes';
}
else
{
echo 'No';
}
This should work :
foreach( $val as $v )
{
if( strpos( $v , $key .'_' ) === true )
{
echo 'yes';
}
else {
echo 'no';
}
}
you can use this
function arraySearch($find_me,$array){
$array2 =array();
foreach ($array as $value) {
$val = explode('_',$value);
$array2[] =$val[0];
}
$Key = array_search($find_me, $array2);
$Zero = in_array($find_me, $array2);
if($Key == NULL && !$Zero){
return false;
}
return $Key;
}
$key = 2; //always a dynamic number
$val = array('3_33', '2_55'); //always a dynamic string with underscore
$inarray = false;
foreach($val as $v){
$arr = explode("_", $val);
$inarray = $inarray || $arr[0] == $key
}
echo $inarray?"Yes":"No";
The given format is quite unpractically.
$array2 = array_reduce ($array, function (array $result, $item) {
list($key, $value) = explode('_', $item);
$result[$key] = $value;
return $result;
}, array());
Now you can the existence of your key just with isset($array2[$myKey]);. I assume you will find this format later in your execution useful too.

PHP set dynamic array index

I have the following key/value from my $_POST variable:
Array
(
'translations_0_comment' => 'Greetings from UK'
)
What I would like is to set this values to the following array
$data[translations][0][comment] = 'Greetings from UK';
So the idea is that I can have anything in my KEY values, and from that I will populate an array.
Is there any safe way to do this without using eval() ?
All help is appreciated.
UPDATE:
this would be the idea with eval()
foreach ($_POST as $key => $dataValue) {
$a = explode("_", $key);
$builder = '$object';
foreach ($a as $value) {
$builder.='['.$value.']';
}
$builder.=' = '.$dataValue.';';
eval($builder);
}
I think you are looking for this
function set_value($object, $paths, $value, $index){
$key = $paths[$index];
$sub_object = $object[$key];
if (!is_array($sub_object)){
$object[$key] = $value;
}else{
$index = $index+1;
$object[$key] = set_value($sub_object, $paths, $value, $index);
}
return $object;
}
explode() is what you need:
$data = array();
foreach ($postData as $key => $val) {
$explodedKey = explode('_', $key);
$data[$explodedKey[0]][$explodedKey[1]][explodedKey[2]] = $val;
}
No need to use eval().
I think this is what you are looking for
Example
In your form which generate the $_POST data rename the input attribute as follows
<input name="data[translations][0][comment]" />
and now your $_POST['data'] will be an array
$data = array();
foreach ($_POST as $keys => $val) {
$keys_list = explode('_', $keys);
$link = &$data;
foreach ($keys_list as $key) {
$link[$key] = $val;
$link = &$link[$key];
}
}
Try this one sir.
$array = array
(
'TRY_THIS_ONE_SIR_PLEASE_THANKS' => 'Greetings from UK'
);
$array1 = array_keys($array);
$arrValue = array_values($array);
$array1 = explode("_", $array1[0]);
$ctr = count($array1);
for($i=0; $i<$ctr; $i++)
{
$start .= "array(\"".$array1[$i]."\" => ";
$end .=")";
}
$start = $start ."\"".$arrValue[0]."\"".$end;
eval("\$arr = $start;");
print_r($arr);

PHP function to get recursive path keys with path

Given an array, I would like a flattened version of the array keys. Each array key would need the 'path' of the array, to that point, appended with an underscore.
An example explains this best.
$arr = array("location"=>0,"details"=>array("width"=>0,"height"=>0,"level"=>array("three"=>0)));
function answer($arr) {....}
the answer function would return this:
array("location","details_width","details_height","details_level_three");
UPDATE:
Here is the work in progress. It will accept an array and return the array keys, but with no depth:
function recursive_keys($input)
{
$output = array_keys($input);
foreach($input as $sub){
if(is_array($sub)){
$output = array_merge($output, recursive_keys($sub));
}
}
return $output;
}
$ritit = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
$results = array();
foreach ($ritit as $leafValue) {
$path = array();
foreach (range(0, $ritit->getDepth()) as $depth) {
$path[] = $ritit->getSubIterator($depth)->key();
}
$results[] = join('_', $path);
}
function recursive_keys(array $array, array $path = array()) {
$result = array();
foreach ($array as $key => $val) {
$currentPath = array_merge($path, array($key));
if (is_array($val)) {
$result = array_merge($result, recursive_keys($val, $currentPath));
} else {
$result[] = join('_', $currentPath);
}
}
return $result;
}
Demo here: http://codepad.viper-7.com/WQ3UYI

How to get values in an array this way with PHP?

From:
$arr = array(array('key1'=>'A',...),array('key1'=>'B',...));
to:
array('A','B',..);
$output = array();
foreach ($arr as $array_piece) {
$output = array_merge($output, $array_piece);
}
return array_values($output);
On the other hand, if you want the first value from each array, what you want is...
$output = array();
foreach ($arr as $array_piece) {
$output[] = array_unshift($array_piece);
}
But I'm thinking you want the first one.
Relatively simple conversion by looping:
$newArray = array()
foreach ($arr as $a) {
foreach ($a as $key => $value) {
$newArray[] = $value;
}
}
Or, perhaps more elegantly:
function flatten($concatenation, $subArray) {
return array_merge($concatenation, array_values($subArray));
}
$newArray = array_reduce($arr, "flatten", array());
John's solution is also nice.
Something like this should work
<?
$arr = array(array('key1'=>'A','key2'=>'B'),array('key1'=>'C','key2'=>'D'));
$new_array = array();
foreach ($arr as $key => $value) {
$new_array = array_merge($new_array, array_values($value));
}
var_export($new_array);
?>
If you want all the values in each array inside your main array.
function collapse($input) {
$buf = array();
if(is_array($input)) {
foreach($input as $i) $buf = array_merge($buf, collapse($i));
}
else $buf[] = $input;
return $buf;
}
Above is a modified unsplat function, which could also be used:
function unsplat($input, $delim="\t") {
$buf = array();
if(is_array($input)) {
foreach($input as $i) $buf[] = unsplat($i, $delim);
}
else $buf[] = $input;
return implode($delim, $buf);
}
$newarray = explode("\0", unsplat($oldarray, "\0"));

Categories