I have this multidimensional array:
$array = array(
'user1' => array('Miguel'),
'user2' => array('Miguel', 'Borges', 'João'),
'user3' => array(
'Sara',
'Tiago' => array('Male')
)
);
I want it flatten, transformed into:
$new_array = array(
'user1.Miguel',
'user2.Miguel',
'user2.Borges',
'user2.João',
'user3.Sara',
'user3.Tiago.Male',
);
Important:
The keys are very important to me. I want them concatenated,
separated by periods.
It should work with any level of nesting.
Thank you!
Though not explicitly stated in your question, it seems that you need to concatenate the string keys and ignore the integer keys (which may be easily achieved with is_string($key)). And since you need your code to “work with any level of nesting,” a recursive function would serve your purpose best:
function array_flatten_key($arr){
$_arr = array();
foreach($arr as $key => $val){
if(is_array($val)){
foreach(array_flatten_key($val) as $_val){
$_arr[] = is_string($key) ? $key.".".$_val : $_val;
}
}
else{
$_arr[] = is_string($key) ? $key.".".$val : $val;
}
}
return $_arr;
}
$new_array = array_flatten_key($array);
print_r($new_array);
The output will be:
Array
(
[0] => user1.Miguel
[1] => user2.Miguel
[2] => user2.Borges
[3] => user2.João
[4] => user3.Sara
[5] => user3.Tiago.Male
)
Related
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();
}
How do I get the value from a subarray? In this case I'm interested in the locale
$objects=
Array
(
[1397300927159026] => Array
(
[category] => 2
[locale] => de_DE
)
[10152395537445743] => Array
(
[category] => 100
[locale] => en_US
)
)
Desired Output:
Array
(
[1397300927159026] => "de_DE"
[10152395537445743] => "en_US"
)
I've tried using a foreach loop to iterate through but the results are a mess -- thanks for any help.
Just a simple foreach would suffice. You just need to create it in another array. Consider this example:
$objects = array(
'1397300927159026' => array('category' => 2, 'locale' => 'de_DE'),
'10152395537445743' => array('category' => 100, 'locale' => 'en_US'),
);
$new_objects = array();
foreach($objects as $key => $value) {
// $key will contain = 1397300927159026, and 1397300927159026
// set that key into the new array as key also
$new_objects[$key] = $value['locale'];
}
echo '<pre>';
print_r($new_objects);
echo '</pre>';
Sample Output:
Array
(
[1397300927159026] => de_DE
[10152395537445743] => en_US
)
This is what array_map() is for. It loops through the array and applies a callback function to each value and returns the modified array.
$objects = array_map( function( $val ) {
return $val['locale'];
}, $objects );
Check this CodeViper Demo
PHP
<?php
$objects=
Array
(
'1397300927159026' => Array
(
'category' => 2,
'locale' => 'de_DE'
),
'10152395537445743' => Array
(
'category' => 100,
'locale' => 'en_US'
)
);
$arr = array();
foreach($objects as $key => $value) {
$arr[$key] = $value['locale'];
}
print_r($arr);
?>
Result
Array ( [1397300927159026] => de_DE [10152395537445743] => en_US )
You can easily do it with a foreach loop and a new array.
Declare a new array say $abc
<?php
$abc = array();
//Going to loop through original array ($objects) as key and values.
foreach($objects as $key => $val ) {
// $key will contain values 1397300927159026, 10152395537445743
// $val['category'] contain values 2,100
// $val['locale'] contain values de_DE, en_US
$abc[$key] = $val['locale'];
}
print_r($abc);
?>
Replace each subarray with its last element's value? array_map() with end() is pretty succinct ...though it requires your application to keep the element at the end of the subarrays -- so arguably less trustworthy.
Also $objects is a poor variable name choice for a multidimensional array.
Code: (Demo)
var_export(array_map('end', $objects));
Output:
array (
1397300927159026 => 'de_DE',
10152395537445743 => 'en_US',
)
I have already read this question and doesn't answer my issue.
I have an Array like this:
Array
(
[0] => Array
(
[COM] => 10659.68
)
[1] => Array
(
[MCD] => 1219.09
)
[2] => Array
(
[MCR] => 77047.65
)
)
And when I make a json_encode() it return this;
[{"COM":10659.68},{"MCD":1219.09},{"MCR":77047.65}]
What I need is get the data in this way:
[["COM":10659.68],["MCD":1219.09],["MCR":77047.65]]
Any idea how can I achieve this
Even though that's not a valid JSON, you can replace the { with [
echo str_replace(array('{','}'),array('[',']'),json_encode($your_array));
Depending on the content you might need a more complex replacement with regular expressions.
More complex solution:
function toJson($arr){
$return = array();
foreach($arr as $k => $v){
if(is_array($v)) $return[] = toJson($v);
else $return[] = sprintf('"%s":%s', $k, $v);
}
return sprintf('[%s]', implode(',', $return));
}
Test:
$input = array(
array('COM' => '10659.68'),
array('MCD' => '1219.09'),
array('MCR' => '77047.65'),
);
var_dump(toJson($input));
string(51) "[["COM":10659.68],["MCD":1219.09],["MCR":77047.65]]"
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.
my php array looks like this:
Array (
[0] => dummy
[1] => stdClass Object (
[aid] => 1
[atitle] => Ameya R. Kadam )
[2] => stdClass Object (
[aid] => 2
[atitle] => Amritpal Singh )
[3] => stdClass Object (
[aid] => 3
[atitle] => Anwar Syed )
[4] => stdClass Object (
[aid] => 4
[atitle] => Aratrika )
) )
now i want to echo the values inside [atitle].
to be specific i want to implode values of atitle into another variable.
how can i make it happen?
With PHP 5.3:
$result = array_map(function($element) { return $element->atitle; }, $array);
if you don't have 5.3 you have to make the anonymous function a regular one and provide the name as string.
Above I missed the part about the empty element, using this approach this could be solved using array_filter:
$array = array_filter($array, function($element) { return is_object($element); });
$result = array_map(function($element) { return $element->atitle; }, $array);
If you are crazy you could write this in one line ...
Your array is declared a bit like this :
(Well, you're probably, in your real case, getting your data from a database or something like that -- but this should be ok, here, to test)
$arr = array(
'dummy',
(object)array('aid' => 1, 'atitle' => 'Ameya R. Kadam'),
(object)array('aid' => 2, 'atitle' => 'Amritpal Singh'),
(object)array('aid' => 3, 'atitle' => 'Anwar Syed'),
(object)array('aid' => 4, 'atitle' => 'Aratrika'),
);
Which means you can extract all the titles to an array, looping over your initial array (excluding the first element, and using the atitle property of each object) :
$titles = array();
$num = count($arr);
for ($i=1 ; $i<$num ; $i++) {
$titles[] = $arr[$i]->atitle;
}
var_dump($titles);
This will get you an array like this one :
array
0 => string 'Ameya R. Kadam' (length=14)
1 => string 'Amritpal Singh' (length=14)
2 => string 'Anwar Syed' (length=10)
3 => string 'Aratrika' (length=8)
And you can now implode all this to a string :
echo implode(', ', $titles);
And you'll get :
Ameya R. Kadam, Amritpal Singh, Anwar Syed, Aratrika
foreach($array as $item){
if(is_object($item) && isset($item->atitle)){
echo $item->atitle;
}
}
to get them into an Array you'd just need to do:
$resultArray = array();
foreach($array as $item){
if(is_object($item) && isset($item->atitle)){
$resultArray[] = $item->atitle;
}
}
Then resultArray is an array of all the atitles
Then you can output as you'd wish
$output = implode(', ', $resultArray);
What you have there is an object.
You can access [atitle] via
$array[1]->atitle;
If you want to check for the existence of title before output, you could use:
// generates the title string from all found titles
$str = '';
foreach ($array AS $k => $v) {
if (isset($v->title)) {
$str .= $v->title;
}
}
echo $str;
If you wanted these in an array it's just a quick switch of storage methods:
// generates the title string from all found titles
$arr = array();
foreach ($array AS $k => $v) {
if (isset($v->title)) {
$arr[] = $v->title;
}
}
echo implode(', ', $arr);
stdClass requires you to use the pointer notation -> for referencing whereas arrays require you to reference them by index, i.e. [4]. You can reference these like:
$array[0]
$array[1]->aid
$array[1]->atitle
$array[2]->aid
$array[2]->atitle
// etc, etc.
$yourArray = array(); //array from above
$atitleArray = array();
foreach($yourArray as $obj){
if(is_object($obj)){
$atitleArray[] = $obj->aTitle;
}
}
seeing as how not every element of your array is an object, you'll need to check for that.