I have a Laravel installed with Moloquent (Mongo). Mongo ins't necessarily the problem, when the model loads the "JSON" record, it becomes a PHP associative array.
I need to be able to create a function in a model that returns an array element by a string.
for example:
$search1 = 'folder1/folder2/folder3/item';
//would look like: $array['folder1'][folder2'][folder3']['item']
$search2 = 'folder1/picture1/picture';
//would look like: $array['folder1'][picture1']['picture']
echo getRecord($search1);
echo getRecord($search2);
function getRecord($str='') {
//this function take path as string and return array
return $result;
}
I guess I could use the ?? operator, but I have to form an array "check" meaning:
How would I form the $array['1']['2']['3'] if I have 3 elements deep or 1 ($array['1']), or 5 ($array['1']['2']['3']['4']['5']).
I am making an api to add an item or folder to Mongo.
Input : "f1/f2/item"
This function I have:
echo print_r($j->_arrayBuilder('f1/f2/item'), true);
public function _arrayBuilder($folderPath)
{
$ret = array();
$arr = explode('/', $folderPath);
Log::info("Path Array:\n" . print_r($arr, true));
$x = count($arr) - 1;
Log::info("Count: " . $x);
for ($i = 0; $i <= $x; $i++) {
Log::info("Element of arr: " . $arr[$i]);
$ret = array($arr[$i] => $ret);
}
return $ret;
}
Current output:
Array
(
[item] => Array
(
[f2] => Array
(
[f1] => Array
(
)
)
)
)
Desire output:
Array
(
[f1] => Array
(
[f2] => Array
(
[item] => Array
(
)
)
)
)
Note: I have tried PHP's array_reverse and it does not work on this.. Multidimensional and non-numeric..
Thank you.
If I understand correctly, You want to take input string f1/f2/f3/f4/f5/item and create array("f1" => array("f2" => array("f3" => array("f4" => array("f5" => array("item" => array()))))))
In order to do that you can use function close to what you tried as:
function buildArr($path) {
$path = array_reverse(explode("/", $path)); // getting the path and reverse it
$ret = array();
foreach($path as $key)
$ret = array($key => $ret);
return $ret;
}
For input of print_r(buildArr("f1/f2/item")); it prints:
Array
(
[f1] => Array
(
[f2] => Array
(
[item] => Array
(
)
)
)
)
Hope that what you meant. If not feel free to comment
Related
I have the following code :
public static function getNatureAndSuffix()
{
foreach (Finder::load('all.yml') as $s => $c) {
$a_games[] = array($c['n'] => $s);
}
return $a_games;
}
The result is :
Array(
[90] => Array
(
[731] => Test1
)
[91] => Array
(
[732] => Test2
)
[92] => Array
(
[735] => Test3
)
)
But I want to get :
Array(
[731] => Test1
[732] => Test1
[735] => Test3
)
So the idea is to obtain an array key=>value. Can you help me please ? Thx in advance
public static function getNatureAndSuffix()
{
foreach (Finder::load('all.yml') as $s => $c) {
$a_games[$c['n']] = $s;
}
return $a_games;
}
explanation:
with: array($c['n'] => $s) you are creating a new array in a array($a_games) what you don't want.
So if you id the index of the first array with the id you get from the loop and give it the value you get from the loop you end up with only a single array.
So the line would be:
$a_games[$c['n']] = $s;
You are setting a new array with those value.
By $a_games[] = array($c['n'] => $s);, it would set as nested array.
Simply do -
$a_games[$c['n']] = $s;
Then the key would be $c['n'] & value be $s in $a_games.
Or you can also do without loop -
$temp = Finder::load('all.yml');
$a_games = array_combine(
array_keys($temp),
array_column($temp, 'n')
);
Note : array_column() is supported PHP >= 5.5
I have a dynamic multidimensional array and I want to convert it to string.
here is an example:
Array
(
[data] => check
[test1] => Array
(
[data] => Hello
)
[test2] => Array
(
[data] => world
)
[test3] => Array
(
[data] => bar
[tst] => Array
(
[data] => Lorem
[bar] => Array
(
[data] => doller
[foo] => Array
(
[data] => sit
)
)
)
)
[test4] => Array
(
[data] => HELLO
[tst] => Array
(
[data] => ipsum
[bar] => Array
(
[data] => Lorem
)
)
)
)
The example for string is:
check&hello&world&bar...lorem&doller...sit ....
I have tried alot of things. I even checked the solutions given on other SO questions. like:
Convert Multidimensional array to single array & Multidimensional Array to String
But No luck.
You can simply use array_walk_recursive like as
$result = [];
array_walk_recursive($arr, function($v) use (&$result) {
$result[] = $v;
});
echo implode('&', $result);
Demo
First convert it to flat array, by
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($input_array));
$flat = iterator_to_array($it, false);
false prevents array key collision.
Then use implode,
$str = implode('&', $flat);
You can use following recursive function to convert any multidimensional array to string
public function _convertToString($data,&$converted){
foreach($data as $key => $value){
if(is_array($value)){
$this->_convertToString($value,$converted);
}else{
$converted .= '&'. $value;
}
}
}
You can call above function in following way:
$str = array(
"data" => "check",
"test1" => array(
"data" => "Hello",
"test3" => array(
"data" => "satish"
)
),
"test2" => array(
"data" => "world"
)
);
$converted = "";
//call your function and pass your array and reference string
$this->_convertToString($str,$converted);
echo $converted;
Output will be following:
check&Hello&satish&world
you can modify code to meet your requirement.
Let me know if any further help required.
php has some build in functions that can do this. Like var_dump, json_encode and var_export. But if you want to control the output more it can be doen with a recursive function
function arrToStr(array $data)
{
$str = "";
foreach ($data as $val) {
if (is_array($val)) {
$str .= arrToStr($val);
} else {
$str .= $val;
}
}
return $str;
}
You can format extra line breaks and spaces at will with this.
I would use recursion for this type of array :
echo visit($your_array);
function visit($val){
if( !is_array($val) ){
return $val;
}
$out="";
foreach($val as $v){
$out.= "&".visit($v);
}
return $out;
}
Say for example I have the following array:
$h = array (
"app" => array (
"level1" => array (
"level2" => array (
"level3" =>3
),
"level4" => array (
"level5" => 2
)
)
)
);
What I wish to do is to create a string for every single sub-array found in here. For example, using the array above, the output would be:
Array
(
[0] => Array
(
[app.level1.level2.level3] => 3
)
[1] => Array
(
[app.level1.level4.level5] => 2
)
)
As you can see, each sub-array is concatenated with a '.' to represent the fact there is a child array with a value assigned given by the last node. Of course the only thing I can think of is to create a recursive function that could handle this, though this is where I'm having some trouble here. Here's what I started working on:
public static function buildString($array, $string ="") {
foreach($array as $h => $k) {
if(is_array($k)) {
$string .= $h.".";
return self::buildString($k, $string);
} else {
$string .= $h;
$j[] = array (
$string => $k
);
return $j;
}
}
}
Inputting the array given above within this method, I successfully get the first iteration:
Array
(
[0] => Array
(
[app.level1.level2.level3] => 3
)
)
And this is where I am at the moment and cannot seem to figure out how to do the rest of the array, or any size array for that matter.
Any hints//remarks would be appreciated.
You cannot return inside the foreach loop, you need to aggregate all of the recursive/non-recursive results and bubble them up. Something like this:
public static function buildString($array, $string ="") {
$j = array();
foreach($array as $h => $k) {
if(is_array($k)) {
$string .= $h.".";
$j = array_merge($j, self::buildString($k, $string));
} else {
$string .= $h;
$j[] = array (
$string => $k
);
}
}
return $j;
}
you can use array_walk() as a method:
$h = array (
"app" => array (
"level1" => array (
"level2" => array (
"level3" =>3
),
"level4" => array (
"level5" => 2
)
)
)
);
$results = array();
function get_strings($item, $key, $old_key = null) {
global $results;
if(is_array($item)) {
array_walk($item, 'get_strings', $old_key . $key . ".");
} else {
$results[$old_key . $key] = $item;
}
}
array_walk($h, 'get_strings');
print_r($results); //returns Array ( [app.level1.level2.level3] => 3 [app.level1.level4.level5] => 2 )
array_walk() documentation: http://php.net/manual/en/function.array-walk.php
Although I must give credit to #kennypu, I've made some slight modifications to the answer in order to contain the code in one function without the use of global or any other variables within the class (keeping it all in one method).
public static function buildString($array, $delimeter = '.') {
$results = array();
$func = function($item, $key, $old_key = NULL) use (&$func, &$results, $delimeter) {
if(is_array($item)) {
array_walk($item, $func, $old_key . $key . $delimeter);
} else {
$results[$old_key . $key] = $item;
}
};
array_walk($array, $func);
return $results;
}
In essence I created an anonymous function that uses parameters from the parent with the use of the key word use. Although not much documentation can be found for use some examples are shown here: Anonymous Functions.
I have the following array:
Array
(
[0] => INBOX.Trash
[1] => INBOX.Sent
[2] => INBOX.Drafts
[3] => INBOX.Test.sub folder
[4] => INBOX.Test.sub folder.test 2
)
How can I convert this array to a multidimensional array like this:
Array
(
[Inbox] => Array
(
[Trash] => Array
(
)
[Sent] => Array
(
)
[Drafts] => Array
(
)
[Test] => Array
(
[sub folder] => Array
(
[test 2] => Array
(
)
)
)
)
)
Try this.
<?php
$test = Array
(
0 => 'INBOX.Trash',
1 => 'INBOX.Sent',
2 => 'INBOX.Drafts',
3 => 'INBOX.Test.sub folder',
4 => 'INBOX.Test.sub folder.test 2',
);
$output = array();
foreach($test as $element){
assignArrayByPath($output, $element);
}
//print_r($output);
debug($output);
function assignArrayByPath(&$arr, $path) {
$keys = explode('.', $path);
while ($key = array_shift($keys)) {
$arr = &$arr[$key];
}
}
function debug($arr){
echo "<pre>";
print_r($arr);
echo "</pre>";
}
I was very interested in this as was having immense difficulty trying to do this. After looking at (and going through) Jon's solution I have come up with this:
$array = array();
function parse_folder(&$array, $folder)
{
// split the folder name by . into an array
$path = explode('.', $folder);
// set the pointer to the root of the array
$root = &$array;
// loop through the path parts until all parts have been removed (via array_shift below)
while (count($path) > 1) {
// extract and remove the first part of the path
$branch = array_shift($path);
// if the current path hasn't been created yet..
if (!isset($root[$branch])) {
// create it
$root[$branch] = array();
}
// set the root to the current part of the path so we can append the next part directly
$root = &$root[$branch];
}
// set the value of the path to an empty array as per OP request
$root[$path[0]] = array();
}
foreach ($folders as $folder) {
// loop through each folder and send it to the parse_folder() function
parse_folder($array, $folder);
}
print_r($array);
I'm trying to use a specific object type from a JSON feed, and am having a hard time specifying it. Using the code below I grab and print the specific array (max) I want,
$jsonurl = "LINK";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json,true);
$max_output = $json_output["max"];
echo '<pre>';
print_r($max_output);
echo '</pre>';
And from the Array below, all I want to work with is the [1] objects in each array. How can I specify and get just those values?
Array
(
[0] => Array
(
[0] => 1309924800000
[1] => 28877
)
[1] => Array
(
[0] => 1310011200000
[1] => 29807
)
[2] => Array
(
[0] => 1310097600000
[1] => 33345
)
[3] => Array
(
[0] => 1310184000000
[1] => 33345
)
[4] => Array
(
[0] => 1310270400000
[1] => 33345
)
[5] => Array
(
[0] => 1310356800000
[1] => 40703
)
Well you could fetch those values with array_map:
$max_output = array_map(function($val) { return $val[1]; }, $json_output["max"]);
This requires PHP 5.3, if you use an earlier version, then you can use create_function to achieve similar results:
$max_output = array_map(create_function('$val', 'return $val[1];'), $json_output["max"]);
When you need to create new array which will contain only second values, you may use either foreach loop which will create it or use array_map() (just for fun with anonymous function available since php 5.3.0):
$newArray = array_map( function( $item){
return $item[1]
},$array);
Then you want to use last ("max" -> considering array with numeric keys) item, you can use end():
return end( $item);
And when you can process your data sequentially (eg. it's not part of some big getData() function) you can rather use foreach:
foreach( $items as $key => $val){
echo $val[1] . " is my number\n";
}
After you get $max_output...
for( $i = 0; $i < length( $max_output ); $i++ ) {
$max_output[$i] = $max_output[$i][1];
}
try this:
$ones = array();
foreach ($max_output as $r)
$ones[] = $r[1];