A
A
amatoriste2018-05-10 11:07:27
PHP
amatoriste, 2018-05-10 11:07:27

How to find nesting in multidimensional array and add elements?

Hello everyone!) I'm a little stuck on the task, I ask for help)
There is an array, for example

"it_array": [
    "select": ["val1", "val2", "val3"],
    "relations": [
      "relation_1_title": [
        "select": ["some_val"],
        "relations": [
          "relation_2_title": [
            "select": ["some_val1", "some_val2"],
            "relations": [
              "relation_3_title": []
            ]
          ]
        ]
      ]
    ]
  ]

How can I find relation_3_title and add key-values ​​there? There can be a lot of such attachments, I need to find and change the last relation without the attachment of the relation (the title of the last relation is known).
On ES6 this can be done easily - via .find, how to do it in php?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
JimmDiGreez, 2018-05-10
@amatoriste

Found on google:
Recursive variant:

function getArray($array, $index) {
    if (!is_array($array)) return null;
    if (isset($array[$index])) return $array[$index];
    foreach ($array as $item) {
        $return = getArray($item, $index);
        if (!is_null($return)) {
            return $return;
        }
    }
    return null;
}

Iterative option:
function getArray($array, $index) {
    $queue = array($array);
    while (($item = array_shift($queue)) !== null) {
        if (!is_array($item)) continue;
        if (isset($item[$index])) return $item[$index];
        $queue = array_merge($queue, $item);
    }
    return null;
}

Source

Y
Yan-s, 2018-05-10
@Yan-s

This is solved using recursion. Look for "php search in multidimensional array by key"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question