• Status: Solved
  • Priority: Low
  • Security: Public
  • Views: 66
  • Last Modified:

Update specific value of key in multidimensional array

i have tried some several way of updating specific array at specific depth in multidimensional array. Although i am able to update but it is not modifying the original array. Even though i tried the referencing technique of php but it seems odds are not in my favour.

// Multidimensional array would be as tree 
    // lets call this array = $tree[$i]['child']
    Array
(
    [0] => Array
        (
            [name] => hasan 
            [clientCode] => 06442
            [somekey] => 707
            [individualCommission] => 10
            [child] => Array
                (
                    [0] => Array
                        (
                            [name] => Aslan
                            [clientCode] => 06447
                            [somekey] => 712
                            [individualCommission] => 10
                        )

                    [1] => Array
                        (
                            [name] => Kudret
                            [clientCode] => 06448
                            [somekey] => 713
                            [individualCommission] => 10
                        )

                    [2] => Array
                        (
                            [name] => Emir
                            [clientCode] => 06446
                            [somekey] => 711
                            [individualCommission] => 10
                        )

                )

        )

    [1] => Array
        (
            [name] => emine
            [clientCode] => 06443
            [somekey] => 708
            [individualCommission] => 10
            [child] => Array
                (
                    [0] => Array
                        (
                            [name] => Kaan
                            [clientCode] => 06449
                            [somekey] => 714
                            [individualCommission] => 10
                        )

                    [1] => Array
                        (
                            [name] => Duygu
                            [clientCode] => 06450
                            [somekey] => 715
                            [individualCommission] => 10
                        )

                    [2] => Array
                        (
                            [name] => Hakan
                            [clientCode] => 06451
                            [somekey] => 716
                            [individualCommission] => 10
                        )

                    [3] => Array
                        (
                            [name] => Yesim
                            [clientCode] => 06452
                            [somekey] => 717
                            [individualCommission] => 10
                        )

                )

        )

    [2] => Array
        (
            [name] => Aysel
            [clientCode] => 06444
            [somekey] => 709
            [individualCommission] => 10
            [child] => Array
                (
                    [0] => Array
                        (
                            [name] => Ismet
                            [clientCode] => 06453
                            [somekey] => 718
                            [individualCommission] => 10
                        )

                    [1] => Array
                        (
                            [name] => Suna
                            [clientCode] => 06454
                            [somekey] => 719
                            [individualCommission] => 10
                        )

                    [2] => Array
                        (
                            [name] => Kudriya
                            [clientCode] => 06455
                            [somekey] => 720
                            [individualCommission] => 10
                        )

                )

        )

    [3] => Array
        (
            [name] => Ali
            [clientCode] => 06445
            [somekey] => 710
            [individualCommission] => 10
            [child] => Array
                (
                    [0] => Array
                        (
                            [name] => Gulen
                            [clientCode] => 06456
                            [somekey] => 721
                            [individualCommission] => 10
                        )

                    [1] => Array
                        (
                            [name] => Halit
                            [clientCode] => 06457
                            [somekey] => 722
                            [individualCommission] => 10
                            [child] => Array
                                (
                                    [0] => Array
                                        (
                                            [name] => Seniz
                                            [clientCode] => 06458
                                            [somekey] => 723
                                            [individualCommission] => 10
                                        )

                                    [1] => Array
                                        (
                                            [name] => Güzin
                                            [clientCode] => 06459
                                            [somekey] => 724
                                            [individualCommission] => 10
                                            [child] => Array
                                                (
                                                    [0] => Array
                                                        (
                                                            [name] => test client
                                                            [clientCode] => 06460
                                                            [somekey] => 725
                                                            [individualCommission] => 10
                                                        )

                                                    [1] => Array
                                                        (
                                                            [name] => test client 2
                                                            [clientCode] => 06461
                                                            [somekey] => 726
                                                            [individualCommission] => 10
                                                        )

                                                )

                                        )

                                )

                        )

                )

        )

)

Open in new window


let's say, the above array is in function A and i passed that above array, which lets say is $tree[$i]['child'], like below:

function A($tree) {
   $i = 5;
   $childArr = &$tree[$i]['child'];
   $childArr = findandReplace($childArr);
   dump($childArr); // still same nothing changed at that specific index of array 
}

Open in new window


I was successfully able to find Specific array using

function findandReplace($array) {

        // Loops through each element. If element again is array, function is recalled. If not, result is echoed.
        foreach($array as $key=>$value)
        { 
            if(is_array($value))
            { 
                findandReplace($value); 
            }
            else{
                if ($key == 'clientCode' && $value == '06459') {
                    // echo $key." = ".$value."<br />\n";
                    $array['individualCommission'] = '10000000000000';                    
                    break;
                }
            } 
        }

        return $array;
    }

Open in new window


so above example i was targeting the array with clientCode = 06459 and if found i was updating its individualCommission key to some value. if i do dump after updating with $array['individualCommission'] = '10000000000000';, it seems, i was able to successfully update it. but unfortunately original array is still same hence unmodified.

Another try i did, it updated that specific array and return that specific array only and i lost all other arrays of multidimensional array.

function findandReplace($array) {    
        $parent = &$array;
        $iterator = new \RecursiveIteratorIterator( new \RecursiveArrayIterator($array), \RecursiveIteratorIterator::SELF_FIRST );
        // $result = array();
        foreach ($iterator as $key => $item) {
            if ( $key === 'clientCode' && $item == '06459') {

                $parent = (array)$iterator->getInnerIterator();
                $parent['individualCommission'] = '1000000000000000';
                // $array[3]['child'][1]['child'][1]['individualCommission'] = $parentCommission;
                break;
            }
        }
        return $array;

    }

Open in new window


so i will appreciate if anyone would spare some time and find any solution for this simple problem.

Thanks!
0
Danish Raza
Asked:
Danish Raza
  • 6
  • 4
2 Solutions
 
Julian HansenCommented:
In a foreach your items are by default value parameters - you need to make the reference so you change this
 foreach($array as $key=>$value)

Open in new window

To this
 foreach($array as $key=>&$value)

Open in new window

Note the '&' in front of the $value - this tells PHP to treat $value as a reference to the value and not the value itself.
2
 
Danish RazaFreelance Full Stack Software DeveloperAuthor Commented:
Hey @Julian thank you for your reply. but if you observed closely in my case i am updating particular $array after verifying if key is clientCode and $value matches clientCode as well.
see this

if ($key == 'clientCode' && $value == '06459') {
                    // echo $key." = ".$value."<br />\n";
                    $array['individualCommission'] = '10000000000000';                    
                    break;
                }

Open in new window


so this is where i am updating "individualCommission" key of that particular array. Although in functionA i did pass this array as refrence.

I tried your comment but i didn't effect anything!
0
 
Danish RazaFreelance Full Stack Software DeveloperAuthor Commented:
YAY! finally after 1 day fight with references finally it working. I found the solution to this trickish problem. Although i was passing array in my findandReplace function as reference but i was doing recursion as well. It was losing reference(i believe) while finding particular array in recursion. answer is to put 2 additional references one in the foreach to
$value

Open in new window

and otherone to
findandReplace(&$array)

Open in new window


so final function would be look like this

function findandReplace(&$array) {
        foreach($array as $key => &$value)
        { 
            if(is_array($value))
            { 
                findandReplace($value); 
            }
            else{
                
                if ($key == 'clientCode' && $value == '06456') {
                    // echo $key." = ".$value."<br />\n";

                    $array['individualCommission'] = '10000000000000';
                    break;
                }
            } 
        }

        return $array;
    }

Open in new window


I hope this will help someone. couldn't find any solution on whole internet!
0
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
Julian HansenCommented:
foreach($array as $key => &$value)

Open in new window

This was exactly what I said here https://www.experts-exchange.com/questions/29088464/Update-specific-value-of-key-in-multidimensional-array.html#a42495810
0
 
Danish RazaFreelance Full Stack Software DeveloperAuthor Commented:
Hi @Julian Hansen yes but if i do not write additional
findandReplace(&$array) 

Open in new window

refrence in function params then it doesn't save back!! It seems to me very weird though but i believe it is because of recursion
0
 
Julian HansenCommented:
Sorry but you implemented a change I recommended on line 2 of your latest code - that was the reason your code was not working NOT BECAUSE OF RECURSION

You were calling this
findandReplace($value); 

Open in new window

With a value parameter

Changing the $value to &$value in the for loop is what was needed to fix the code - which I recommended, you implemented and now it is working.

I don't understand why you are saying you did not get a solution!
0
 
Danish RazaFreelance Full Stack Software DeveloperAuthor Commented:
why don't you go ahead and try what you commented about & sign next to $value. you did provide aid to solution for which i am thankful. but indeed your recommendation didn't solve my problem. also it is not the case that i didn't think of putting & sign in foreach. i did try myself many other combinations!

I will admit i just luckily solve it while tracing and putting a & in function findandreplace()
0
 
Julian HansenCommented:
Try calling findandreplace(&$array) with your foreach set to $value - it won't work.

also it is not the case that i didn't think of putting & sign in foreach. i did try myself many other combinations!
You never mentioned this in your OP.

Anyway I wish you well with your project
0
 
Danish RazaFreelance Full Stack Software DeveloperAuthor Commented:
thanks for help @Julian. Highly appreciated your effort!!
0
 
Danish RazaFreelance Full Stack Software DeveloperAuthor Commented:
problem solved!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Office 2010

This course will introduce you to the interfaces and features of Microsoft Office 2010 Word, Excel, PowerPoint, Outlook, and Access. You will learn about the features that are shared between all products in the Office suite, as well as the new features that are product specific.

  • 6
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now