duanchuiwen6694
duanchuiwen6694
2019-01-07 13:13

从字符串为Mongo创建PHP数组

已采纳

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:
" . 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.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dpoh61610 dpoh61610 2年前

    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

    点赞 评论 复制链接分享

为你推荐