Joe Merra
Joe Merra

Reputation: 29

How to get deep key in array php?

If a have an array:

Array
(
    [1-title1] => Array
        (
            [0] => title = title erer
            [1] => 1-title1
            [2] => content = content 1
        )

    [2-title2] => Array
        (
            [0] => title = title dffgfghfdg
            [1] => 2-title2
            [2] => content = content 2
        )

and I want to get array:

Array
(
    [1-title1] => Array
        (
            [title] =>title erer
            [1] =>title1
            [content] =>content 1
        )

    [2-title2] => Array
        (
            [title] =>title dffgfghfdg
            [2] => title2
            [content] =>content 2
        )

What should I do?

Upvotes: 0

Views: 1436

Answers (3)

Philippe Gerber
Philippe Gerber

Reputation: 17836

A solution without references and no implicit key names.

foreach ($array as $key => $innerArray) {
    foreach ($innerArray as $innerKey => $value) {
        if (false !== strpos($value, ' = ')) {
            unset($array[$key][$innerKey]);
            list($innerKey, $value) = explode(' = ', $value, 2);
            $array[$key][$innerKey] = $value;
        }
    }
}

Upvotes: 1

Robin Michael Poothurai
Robin Michael Poothurai

Reputation: 5664

try this

foreach($array as $ky=>$val)  {
  echo $ky;
  var_dump(array_keys($val));
}

Upvotes: 0

Savid
Savid

Reputation: 311

foreach($array as &$title){
    $newTitle = array();
    $titleName = explode(' = ', $title[0] , 2);
    $newTitle['title'] = end($titleName);
    $titleNum = explode('-', $title[1] , 2);
    $newTitle[$titleNum[0]] = $titleNum[1];
    $titleContent = explode(' = ', $title[2] , 2);
    $newTitle['content'] = end($titleContent);  
    $title = $newTitle;
}

Upvotes: 0

Related Questions