DobotJr DobotJr - 5 months ago 9
PHP Question

Create multidimensional array out of long string PHP

Say I have a string like this:

all:ticket_location:is:5|||all:ticket_sub_location:is:1|||any:ticket_is:created:NULL|||any:ticket_is:updated:NULL|||action:assigned_agent_uid:admin


I need an array that looks something like this:

array(
[all] => Array
(
[ticket_location] => Array (
[is]=>5
)
[ticket_sub_location] => Array (
[is]=>1
)
)
[any] => Array
(
[ticket_is] => Array (
[created] => NULL
)
[ticket_is] => Array (
[updated] => NULL
)
)
[action] => Array
(
[assigned_agent_ui] => Admin
)
)


This is my code so far but I'm failing miserably. Hard for me to wrap my head around multidimensional arrays.

$trigger_data = "all:ticket_location:is:5|||all:ticket_sub_location:is:1|||any:ticket_is:created:NULL|||any:ticket_is:updated:NULL|||action:assigned_agent_uid:admin";

$parts = explode("|||",$trigger_data);
$rules = array();
$actions = array();
foreach($parts as $value) {
$pieces = explode(":",$value);
if ($pieces[0] == "all" || $pieces[0] == "any") {
$rules[$pieces[0]][$pieces[1]][$pieces[2]] = $pieces[3];
}
if ($pieces[0] == "action") {
$actions[$pieces[0]][$pieces[1]] = $pieces[2];
}

}

print_r($pieces);
print_r($actions);
exit;

Answer

Before anything else, you can't have both ticket_is keys in the same dimension inside any. Anyway, just use references, so that you can create your keys continually on the necessary depth, then use explode when needed:

$trigger_data = "all:ticket_location:is:5|||all:ticket_sub_location:is:1|||any:ticket_is:created:NULL|||any:ticket_is:updated:NULL|||action:assigned_agent_uid:admin";
$final = array();
foreach(explode('|||', $trigger_data) as $e) {
    $e = explode(':', $e);
    $result = &$final;
    $value = end($e);
    foreach($e as $parts) {
        if($value === $parts) {
            $result = $value;
        } else {
            $result = &$result[$parts]; 
        }

    }
}

print_r($final);

Out

Comments