-2

I have below array, I need to append a new array inside $newData['_embedded']['settings']['web/vacation/filters']['data'], How can I access and append inside it ?

$newData  = [ 
  "id" => "47964173",
  "email" => "[email protected]",
  "firstName" => "Muhammad",
  "lastName" => "Taqi",
  "type" => "employee",
  "_embedded" => [
      "settings" => [
    [
        "alias" => "web/essentials",
        "data" => [],
        "dateUpdated" => "2017-08-16T08:54:11Z"
    ],
    [
        "alias" => "web/personalization",
        "data" => [],
        "dateUpdated" => "2016-07-14T10:31:46Z"
    ],
    [
        "alias" => "wizard/login",
        "data" => [],
        "dateUpdated" => "2016-09-26T07:56:43Z"
    ],
    [
        "alias" => "web/vacation/filters",
        "data" => [
          "test" => [
            "type" => "teams",
            "value" => [
              0 => "09b285ec-7687-fc95-2630-82d321764ea7",
              1 => "0bf117b4-668b-a9da-72d4-66407be64a56",
              2 => "16f30bfb-060b-360f-168e-1ddff04ef5cd"
            ],
          ],
          "multiple teams" => [
            "type" => "teams",
            "value" => [
              0 => "359c0f53-c9c3-3f88-87e3-aa9ec2748313"
            ]
          ]
        ],
        "dateUpdated" => "2017-07-03T09:10:36Z"
      ],
    [
        "alias" => "web/vacation/state",
        "data" => [],
        "dateUpdated" => "2016-12-08T06:58:57Z"
    ]
    ]
  ]
];

$newData['_embedded']['settings']['web/vacation/filters']['data'] = $newArray;

Any Hint to quickly append it, I don't want to loop-in and check for keys inside loops.

2

2 Answers 2

1

The settings subarray is "indexed". You first need to search the alias column of the subarray for web/vacation/filters to find the correct index. Using a foreach loop without a break will mean your code will continue to iterate even after the index is found (bad coding practice).

There is a cleaner way that avoids a loop & condition & break, use array_search(array_column()). It will seek your associative element, return the index, and immediately stop seeking.

You can use the + operator to add the new data to the subarray. This avoids calling a function like array_merge().

Code: (Demo)

if(($index=array_search('web/vacation/filters',array_column($newData['_embedded']['settings'],'alias')))!==false){
    $newData['_embedded']['settings'][$index]['data']+=$newArray;
}
var_export($newData);

Perhaps a more considered process would be to force the insert of the new data when the search returns no match, rather than just flagging the process as unsuccessful. You may have to tweak the date generation for your specific timezone or whatever... (Demo Link)

$newArray=["test2"=>[
            "type" =>"teams2",
            "value" => [
              0 => "09b285ec-7687-fc95-2630-82d321764ea7",
              1 => "0bf117b4-668b-a9da-72d4-66407be64a56",
              2 => "16f30bfb-060b-360f-168e-1ddff04ef5cd"
            ],
          ]
          ];
if(($index=array_search('web/vacation/filters',array_column($newData['_embedded']['settings'],'alias')))!==false){
    //echo $index;
    $newData['_embedded']['settings'][$index]['data']+=$newArray;
}else{
    //echo "couldn't find index, inserting new subarray";
    $dt = new DateTime();
    $dt->setTimeZone(new DateTimeZone('UTC'));  // or whatever you are using
    $stamp=$dt->format('Y-m-d\TH-i-s\Z');

    $newData['_embedded']['settings'][]=[
                                            "alias" => "web/vacation/filters",
                                            "data" => $newArray,
                                            "dateUpdated" => $stamp
                                        ];
}
Sign up to request clarification or add additional context in comments.

4 Comments

@mtaqi This is the way that you are "supposed" to do it. The foreach loop in jh1711's answer doesn't include an exit, so it continues to iterate even after it has sucessfully added the new data. My way also avoids the call of array merge.
I guess we should add that my loop returns the index of the last occurence of the alias, while your array_search returns the first. Maybe we could also mention that array_merge replaces values with the same index, while the union operator doesn't. But everybody always wants first and old, and not last and new, or God forbid a combination.
The OP's input data does not suggest that there will be multiple matches, so there is no benefit in searching for multiple occurrences. If we are going to discuss theoretical extensions of the question, then I should note that if the targeted subarray is not found, your methods will generate: <b>Notice</b>: Undefined variable: indexOfWVF and insert a non-indexed subarray (the key is an empty string).
Touche. The difference between array_merge and the union operator, could still interest somebody. But I'll admit that it's only an edge case.
1

You need to find the key that corresponds to web/vacation/filters. For Example you could use this.

foreach ($newData['_embedded']['settings'] as $key => $value) {
 if ($value["alias"]==='web/vacation/filters') {
   $indexOfWVF = $key;
 }
}
$newData['_embedded']['settings'][$indexOfWVF]['data'][] = $newArray;

From the comments. Then you want to merge the arrays. Not append them.

$newData['_embedded']['settings'][$indexOfWVF]['data'] = array_merge($newData['_embedded']['settings'][$indexOfWVF]['data'],$newArray);

Or (if it's always Filter1):

  $newData['_embedded']['settings'][$indexOfWVF]['data']['Filter1'] = $newArray['Filter1'];

4 Comments

It becomes this now ``` "alias" => "web/vacation/filters" "data" => [ "test" => [] "multiple teams" => [] 0 => [ "Filter1" => [] ] ]```
Filter1 is the new array. It should be as ` "alias" => "web/vacation/filters" "data" => [ "test" => [] "multiple teams" => [] "Filter1" => [] ]`
Good example. Alternately, make the array structure work for you.
@mtaqi. I edited the answer with 2 suggestions that should work. You need to keep the for loop for both of them

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.