skip to Main Content

So I have a multidimensional array like the one below:

[0]=>
  array(4) {
    ["id"] => 110
    ["list"] => {}
    ["MainProduct"] => 2         <- Step2: Replace the 2 with a 5 where productName is Oranges
    ["productName"] => Oranges   <- Step1: Find where we have "Oranges"
  }
[1]=>
  array(4) {
    ["id"] => 111
    ["list"] => {}
    ["MainProduct"] => 110
    ["productName"] => Apples
  }

Ultimately, what I need to achieve is to find were the value for key productName equals Oranges and based on that to replace the value for key MainProduct in the same sub array.

I thought I should first find the index for the array containing Oranges and then replace the value for key mainProduct but can’t seem to do it properly.
They key names are always the same, while the value names are different.

Also, the array is dynamic so the array with Oranges won’t always have the same index.

This is the desired result:

[0]=>
  array(4) {
    ["id"] => 110
    ["list"] => {}
    ["MainProduct"] => 5         <- This is changed to 5 where productName is "Oranges"
    ["productName"] => Oranges   
  }
[1]=>
  array(4) {
    ["id"] => 111
    ["list"] => {}
    ["MainProduct"] => 110
    ["productName"] => Apples
  }

2

Answers


  1. A slight variant of the strategy you proposed:

    <?php
    $data = [
      [
        "id" => 110,
        "MainProduct" => 2,
        "productName" => "Oranges",
      ],
      [
        "id" => 111,
        "MainProduct" => 110,
        "productName" => "Apples",
      ]
    ];
    
    $output = [];
    array_walk($data, function(&$entry) use($data)  {
      $mainProduct = array_search($entry['MainProduct'], $data);
      $entry['productName'] = $data[$mainProduct]['productName'];
    });
    
    print_r($data);
    

    The output is:

    Array
    (
        [0] => Array
            (
                [id] => 110
                [MainProduct] => 2
                [productName] => Oranges
            )
        [1] => Array
            (
                [id] => 111
                [MainProduct] => 110
                [productName] => Oranges
            )
    )
    
    Login or Signup to reply.
  2. If you get the keys and combine with the productName values, then you can search it and get the key. Then use the key to update MainProduct:

    $array[array_search('Oranges', array_combine(array_keys($array), array_column($array, 'productName')))]['MainProduct'] = 5;
    

    If productName is unique, then I would just modify the array to index on that:

    $array = array_column($array, null, 'productName');
    $array['Orange']['MainProduct'] = 5;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search