stevenpepe
stevenpepe

Reputation: 267

PHP loop through multidimensional array and change values

I have a multidimensional array below and I want to loop through it and change the value of [menu_cats] from a number to a string, which is being pulled from a database selection. Is this possible? The name of the array is 'result'.

Array
(
[0] => Array
    (
        [0] => Array
            (
                [menu_cats] => 1                    
                [item] => Introduction
                [link] => needs
            )

        [1] => Array
            (
                [menu_cats] => 1
                [item] => Needs Assessment
                [link] => needs/needs.php
            )

    )

[1] => Array
    (
        [0] => Array
            (
                [menu_cats] => 2                    
                [item] => Introduction
                [link] => knowledge
            )

        [1] => Array
            (
                [menu_cats] => 2
                [item] => Administer Knowledge Pre-Test
                [link] => knowledge/pre_test.php
            )
    )

)

Upvotes: 7

Views: 9896

Answers (3)

Roberto Braga
Roberto Braga

Reputation: 559

Fastest and best option is to use array_walk_recursive(), it is a native php function therefore is much faster than any other php coded solution:

array_walk_recursive(
    $array,
    static function (&$value, $key) {
        if ($key==='menu_cats') {
            $value = 'new value';
        }
    }
);

Upvotes: 0

hoangthienan
hoangthienan

Reputation: 866

You can loop through all JSON Arrays by using a recursive algorithm

$menuData = [
    [
        ['menu_cats' => 1, 'item' => 'Introduction', 'link' => 'needs'],
        ['menu_cats' => 1, 'item' => 'Needs Assessment', 'link' => 'needs/needs.php'],
    ],
    [
        ['menu_cats' => 2, 'item' => 'Introduction', 'link' => 'knowledge'],
        ['menu_cats' => 2, 'item' => 'NeedsAdminister Knowledge Pre-Test', 'link' => 'needsknowledge/pre_test.php'],
    ],
];

recursiveArray($menuData);
print_r($menuData);

# A recursive function to traverse the $rowData array
function recursiveArray(array &$rowData)
{
    foreach ($rowData as $key => &$hitElement) {
        # If there is a element left
        if (is_array($hitElement)) {
            # call recursive structure to parse the $rowData
            recursiveArray($hitElement);
        } else {
            if ($key === 'menu_cats') {
                $hitElement = 'new value';
            }
        }
    }
}

Live code -> https://wtools.io/php-sandbox/bFER

OR use the RecursiveArrayIterator to traverse the $menuData array

Upvotes: 0

Marc B
Marc B

Reputation: 360922

foreach($result as $key => $subarray) {
   foreach($subarray as $subkey => $subsubarray) {
      $result[$key][$subkey]['menu_cats'] = 'your string here';
   }
}

Upvotes: 11

Related Questions