Reproducing the new array from existing array(multi array)
If I have an array called as parameter:
$arr = Array
(
[0] => Array(0,Array(0=>'abc'))
[1] => Array(0,Array(1=>'def'))
[2] => Array(1,Array(0=>'ghi'))
)
Want to to a function that pass $arr some thing like this
function TODO($arr){
//
return $new_array;
}
And the function will return
RESULT WILL BE Reproduce elements from previous array ,And it will be got the result(returned):
Array
(
[0] => Array
(
[0] => 'abc'
[1] => 'def'
)
[1] => Array
(
[0] => 'ghi'
)
)
Anybody know how to do this?Please
thanks
I'm not 100% sure I've understood what you want, but if I have, this should work:
<?php
$arr = Array(
0 => Array(0, Array(0=>'abc')),
1 => Array(0, Array(1=>'def')),
2 => Array(1, Array(0=>'ghi'))
);
function transformArray($array) {
$newArray = array();
foreach ($array as $value) {
if (!isset($newArray[$value[0]])) {
$newArray[$value[0]] = array();
}
$newArray[$value[0]][] = array_pop($value[1]);
}
return $newArray;
}
$outputArray = transformArray($arr);
echo '<pre>' . print_r($outputArray, true) . '</pre>';
?>
I don't think so. If you have controll over how these text arrays are turned into text, you should use serialize() and unserialize(). The fastest and easiest way.
If you still need to create arrays from the strings you have provided, you will probably have to construct quite a complex function to do that.
Related
I have an existing array in this following structure,
Array
(
[0] => 1
[1] => 3
)
And, I want to convert in the following structure:
Array
(
[0] => Array
(
[class_id] => 1
)
[1] => Array
(
[class_id] => 3
)
)
Any suggestions, please let me know.
Thanks in advance!
Use a map to iterate over the array items and return a new array for each one of them.
<?php
function map($n) {
return [
'class_id' => $n
];
}
$a = array(1, 3);
$b = array_map("map", $a);
print_r($b);
?>
U just need to foreach this like this:
$data = [1, 3];
$result = [];
foreach ($data as $item) {
$result[] = ["class_id" => $item];
}
Seems that is exactly u need )
One liner:
array_walk($data, function(&$n){ $n = ['class_id'=>$n]; })
Keep in mind that we:
Pass the array as a reference to array_walk.
Then we pass each element as a reference to modify its content.
Also, array_walk keeps your index intact.
Hello I want to put values of single array into a multidimensional array with each value on a n+1
This is my array $structures
Array
(
[0] => S
[1] => S.1
[2] => S-VLA-S
[3] => SB
[4] => SB50
)
What I want for output is this
Array
(
[S] => Array(
[S.1] => Array (
[S-VLA-S] => Array (
[SB] => Array (
[SB50] => Array(
'more_attributes' => true
)
)
)
)
)
)
This is what I have tried so far
$structures = explode("\\", $row['structuurCode']);
foreach($structures as $index => $structure) {
$result[$structure][$structure[$index+1]] = $row['structuurCode'];
}
The values of the array is a tree structure that's why it would be handy to have them in an multidimensional array
Thanks in advance.
It becomes pretty trivial once you start turning it inside out and "wrap" the inner array into successive outer arrays:
$result = array_reduce(array_reverse($structures), function ($result, $key) {
return [$key => $result];
}, ['more_attributes' => true]);
Obviously a more complex solution would be needed if you needed to set multiple paths on the same result array, but this is the simplest solution for a single path.
Slightly different approach:
$var = array('a','an','asd','asdf');
$var2 = array_reverse($var);
$result = array('more_attributes' => true);
$temp = array();
foreach ($var2 as $val) {
$temp[$val] = $result;
$result = $temp;
$temp = array();
}
I am working on a big script which will generate some string or array or multidimensional array i want use mysql_real_escape_string for all array / string
for that this i tried the below code
function check($data) {
if(!is_array($data)) {
return mysql_real_escape_string($data);
} else if (is_array($data)) {
$newData = array();
foreach($data as $dataKey => $dataValue){
if(!is_array($dataValue)){
$key = mysql_real_escape_string($dataKey);
$value = mysql_real_escape_string($dataValue);
$newData[$key] = $value;
}
}
return $newData;
}
}
if i use like this check('saveme'); this returns value
if i pass a array it returns corrent value [ check(array('a','b','c',1,2,3)) ]
if i pass multidimensional array i get [check(array(array('a',array('a','b','c',1,2,3),'c',1,2,3),'b',array('a','b','c',1,2,3),1,2,3))]
A kind note i want to use mysql_real_escape_string for array key too.
You can use array_walk_recursive function, to go throw all leaves of the array, and escape values:
array_walk_recursive($array, function(&$leaf) {
if (is_string($leaf))
$leaf = mysql_real_escape_string($leaf);
});
Also, it is good to follow data consistency rules, and do not use !is_array(), but is_string(), because mysql_real_escape_string takes string params, not !string.
Unfortunately, array_walk_recursive is designed so, that it can't edit keys. If you need edit keys, you may want to write your own recursive function. I don't want to copy answer, you can find it here
You can use this function :
(MyStringEscapeFunc() is your custom escape function)
function escape_recursive($arr){
if(is_array($arr)){
$temp_arr = array();
foreach ($arr as $key=>$value){
$temp_arr[MyStringEscapeFunc($key)] = escape_recursive($value);
}
return $temp_arr;
}else{
return MyStringEscapeFunc($arr);
}
}
Example Result :
//Before :
Array (
[0] => Array (
[0] => foo'bar
[1] => bar'baz
)
[1] => foob'ar
[2] => Array ( [foo'baz] => baz'foo )
)
//After :
Array (
[0] => Array (
[0] => foo\'bar
[1] => bar\'baz
)
[1] => foob\'ar
[2] => Array ( [foo\'baz] => baz\'foo )
)
Which method is best practice to turn a multidimensional array
Array ( [0] => Array ( [id] => 11 ) [1] => Array ( [id] => 14 ) )
into a simple array? edit: "flattened" array (thanks arxanas for the right word)
Array ( [0] => 11 [1] => 14 )
I saw some examples but is there an easier way besides foreach loops, implode, or big functions? Surely there must a php function that handles this. Or not..?
$array = array();
$newArray = array();
foreach ( $array as $key => $val )
{
$temp = array_values($val);
$newArray[] = $temp[0];
}
See it here in action: http://viper-7.com/sWfSbD
Here you have it in function form:
function array_flatten ( $array )
{
$out = array();
foreach ( $array as $key => $val )
{
$temp = array_values($val);
$out[] = $temp[0];
}
return $out;
}
See it here in action: http://viper-7.com/psvYNO
You could use array_walk_recursive to flatten an array.
$ret = array();
array_walk_recursive($arr, function($var) use (&$ret) {
$ret[] = $var;
});
var_dump($ret);
If you have a multidimensional array that shouldn't be a multidimensional array (has the same keys and values) and it has multiple depths of dimension, you can just use recursion to loop through it and append each item to a new array. Just be sure not to get a headache with it :)
Here's an example. (It's probably not as "elegant" as xdazz", but it's an alternate without using "use" closure.) This is how the array might start out like:
Start
array (size=2)
0 =>
array (size=1)
'woeid' => string '56413072' (length=8)
1 =>
array (size=1)
'woeid' => string '56412936' (length=8)
Then you might want to have something like this:
Target
array (size=2)
0 => string '56413072' (length=8)
1 => string '56412936' (length=8)
You can use array_walk_recursive
Code
$woeid = array();
array_walk_recursive($result['results']['Result'], function ($item, $key, $woeid) {
if ($key == 'woeid') {
$woeid[] = $item;
}
}, &$woeid);
I have this multidimensional array:
Array (
[0] => Array (
[id] => 1
[list_name] => List_Red
)
[1] => Array (
[id] => 2
[list_name] => List_Blue
)
)
...and i would like to create a new array containing only the [id]'s from it.
I would appreciate it alot if you guys could help me with that ^^
Thanks in advance.
#fabrik Your solution indeed does work but it is also incorrect as PHP will throw a E_WARNING telling you that you're appending to an array that did not yet exist. Always initialise your variables before you use them.
$newList = array();
foreach($myList as $listItem) {
$newList[$listItem['id']] = $listItem['list_name'];
}
This is now a list of all your list_names in the following format.
Array (
1 => List_Red
2 => List_Blue
)
Much easier for you to work with and you can now iterate over it like so..
foreach($newList as $itemID => $itemName) {
echo "Item ID: $itemID - Item Name: $itemName<br>";
}
You could use array_map like this:
$new_array = array_map( function( $a ) { return $a['id']; }, $orig_array );
That's assuming PHP 5.3, for PHP < 5.3 you have to use create_function:
$new_array = array_map( create_function( '$a', 'return $a["id"];' ), $orig_array );
foreach($array as $label => $data)
{
$final[] = $data['id'];
}