Quick actions

cmd+k|ctrl+k

Navigation

Languages

Array PathCallback

Snippet info

Language

Php

Visibility

public

Author

legacy-v1-2949

Created

2018-09-09T15:29:20Z

Updated

2018-09-09T15:29:36Z

<?php

/**
 * $path key.*.username *.password, *.1.username
 */
function pathCallback($path, array $data, $callback, $history = null) {

        $parts = explode(".", $path);
        $first = array_shift($parts);
        $current = null;

        if ($first === "*") {
            $current = $data;
        } else if (is_numeric($first)) {
            $current = [array_values($data)[$first]];
        } else {
            $current = [$data[$first]];
        }


        $results = [];
        $nextPath = implode(".", $parts);
        
        $history .= ($history !== null ? "." : "") . $first;


        foreach ($current as $key => $value) {
            $nextHistory = str_replace("*", $key, $history);
            if (!empty($parts)) {
                $res = pathCallback($nextPath, $value, $callback, $nextHistory);
            } else {
                $res = [$nextHistory => $callback($value)];
            }

            $results = array_merge($results, $res);
        }

        return $results;
    }

$data = [
    [
        "username" => "user1",
        "address" => [
            "street" => "street 1",
            "postal" => "12345",
            "city" => "city123",
            "country" => [
                "code" => "DE",
                "name" => "Germany",
                "locale" => "de_DE"
            ]
        ]
    ],
    [
        "username" => "user2",
        "address" => [
            "street" => "street 2",
            "postal" => "54321",
            "city" => "city123",
            "country" => [
                "code" => "DE",
                "name" => "Germany",
                "locale" => "de_DE"
            ]
        ]
    ]
];

    $d = pathCallback("*.address.country.code", $data, function($v) { return "prefix_$v"; })    ;

var_dump($d);


INFO