1

Arr::add doesn't work with dot notation. Arr::set will create a new element only if it does not exist, otherwise, it will overwrite the existing one. There is data_set, it works similar to Arr::set, but it accepts the overwrite flag which does not do what I need (if it's set to false instead of adding a new item, it will just skip setting new value).

My code:

   $array = [['name' => 'Test', 'link' => 'test_link'], ['name' => 'Test1', 'link' => 'test1_link']];

   $result = [];
   $position = 1;
   foreach($array as $element) {
      Arr::set($result, 'itemListElement.type', 'ListItem');  
      Arr::set($result, 'itemListElement.position', $position);  
      Arr::set($result, 'itemListElement.item.name', $element['name']);  
      Arr::set($result, 'itemListElement.item.link', $element['link']);  
      $position++;
   }

And I would like to have multiple list elements within the itemListElement parent, instead of having one list element which is being overwritten all the time.

Here is what it should look like:

[
    "itemListElement" => [
        [
            "type" => "ListItem",
            "position" => 1,
            "item" => [
                "name" => "Test",
                "url" => "test_url",
            ]
        ],
        [
            "type" => "ListItem",
            "position" => 1,
            "item" => [
                "name" => "Test1",
                "url" => "test1_url",
            ]
        ],
    ]
]

1 Answer 1

1

Can you try this:

 $array = [['name' => 'Test', 'link' => 'test_link'], ['name' => 'Test1', 'link' => 'test1_link']];

   $result = [];
   foreach($array as $key=>$element) {
      Arr::set($result["itemListElement"][$key], 'type', 'ListItem');  
      Arr::set($result["itemListElement"][$key], 'position', $key + 1);  
      Arr::set($result["itemListElement"][$key], 'item.name', $element['name']);  
      Arr::set($result["itemListElement"][$key], 'item.link', $element['link']);  
   }

$result;
Sign up to request clarification or add additional context in comments.

Comments

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.