Issue with array merging/inserting feature not functioning as expected

Here are two arrays that I have:

First Array: 
"workingHours": [
                {
                    "opening": "09:30",
                    "closing": "13:30",
                    "dayName": "sunday"
                },
                {
                    "opening": "",
                    "closing": "",
                    "dayName": "monday"
                },
                {
                    "opening": "",
                    "closing": "",
                    "dayName": "tuesday"
                },
                {
                    "opening": "10:30",
                    "closing": "06:30",
                    "dayName": "wednesday"
                },
                {
                    "opening": "01:00",
                    "closing": "08:00",
                    "dayName": "thursday"
                },
                {
                    "opening": "",
                    "closing": "",
                    "dayName": "friday"
                },
                {
                    "opening": "",
                    "closing": "",
                    "dayName": "saturday"
                },
            ],
Second Array: 
            "discount": [
                {
                    "from_time": "13:00:00",
                    "to_time": "14:50:00",
                    "discount": "20",
                    "dayName": "wednesday"
                },
                {
                    "from_time": "06:13:16",
                    "to_time": "04:14:11",
                    "discount": "20",
                    "dayName": "monday"
                },
                {
                    "from_time": "05:10:15",
                    "to_time": "06:10:17",
                    "discount": "20",
                    "dayName": "tuesday"
                },
                {
                    "from_time": "06:59:16",
                    "to_time": "04:19:11",
                    "discount": "20",
                    "dayName": "monday"
                }
            ],

I need the output to be like this:

Desired Output: 
 "workingHours": {
    "opening": "",
    "closing": "",
    "dayName": "monday"
    {
        "from_time": "06:13:16",
        "to_time": "04:14:11",
        "discount": "20",
        "dayName": "monday"
    },
    {
        "from_time": "06:59:16",
        "to_time": "04:19:11",
        "discount": "20",
        "dayName": "monday"
    }
},
Current Output: 

"workingHours": [
                {
                    "opening": "09:30",
                    "closing": "13:30",
                    "dayName": "sunday"
                },
                {
                    "0": {
                        "from_time": "06:13:16",
                        "to_time": "04:14:11",
                        "discount": "20",
                        "dayName": "monday"
                    },
                    "1": {
                        "from_time": "06:59:16",
                        "to_time": "04:19:11",
                        "discount": "20",
                        "dayName": "monday"
                    },
                    "opening": "",
                    "closing": "",
                    "dayName": "monday"
                },
                {
                    "0": {
                        "from_time": "05:10:15",
                        "to_time": "06:10:17",
                        "discount": "20",
                        "dayName": "tuesday"
                    },
                    "opening": "",
                    "closing": "",
                    "dayName": "tuesday"
                },
                {
                    "0": {
                        "from_time": "13:00:00",
                        "to_time": "14:50:00",
                        "discount": "20",
                        "dayName": "wednesday"
                    },
                    "opening": "10:30",
                    "closing": "06:30",
                    "dayName": "wednesday"
                },
                {
                    "opening": "01:00",
                    "closing": "08:00",
                    "dayName": "thursday"
                },
                {
                    "opening": "",
                    "closing": "",
                    "dayName": "friday"
                },
                {
                    "opening": "",
                    "closing": "",
                    "dayName": "saturday"
                }
            ],

My existing code is as follows:


    foreach ($returnDataAns['workingHours'] as $key => $value) {
        
        foreach ($returnDataAns['discount'] as $key2 => $value2) {

            if ($value['dayName'] == $value2['dayName']) {
                
                array_push($returnDataAns['workingHours'][$key], $value2);
            }

        }
    }

Is there a way to modify this code and remove the 0: 1: keys?

Answer №1

To achieve the desired result, follow this code snippet:

$arr1 = json_decode('[
        {
            "opening": "09:30",
            "closing": "13:30",
            "dayName": "sunday"
        },
        {
            "opening": "",
            "closing": "",
            "dayName": "monday"
        },
        {
            "opening": "",
            "closing": "",
            "dayName": "tuesday"
        },
        {
            "opening": "10:30",
            "closing": "06:30",
            "dayName": "wednesday"
        },
        {
            "opening": "01:00",
            "closing": "08:00",
            "dayName": "thursday"
        },
        {
            "opening": "",
            "closing": "",
            "dayName": "friday"
        },
        {
            "opening": "",
            "closing": "",
            "dayName": "saturday"
        }
    ]', true);

$arr2 = json_decode('[
        {
            "from_time": "13:00:00",
            "to_time": "14:50:00",
            "discount": "20",
            "dayName": "wednesday"
        },
        {
            "from_time": "06:13:16",
            "to_time": "04:14:11",
            "discount": "20",
            "dayName": "monday"
        },
        {
            "from_time": "05:10:15",
            "to_time": "06:10:17",
            "discount": "20",
            "dayName": "tuesday"
        },
        {
            "from_time": "06:59:16",
            "to_time": "04:19:11",
            "discount": "20",
            "dayName": "monday"
        }
    ]', true);

$finalArray = [];
foreach ($arr1 as $key => $day) {
    $subArray = [];
    foreach ($arr2 as $key2 => $dayData) {
        if ($day['dayName'] === $dayData['dayName']) {
            $subArray[] = $dayData;
        }
    }
    $finalArray[$key] = !empty($subArray) ? $finalArray[$key] = [$day, $subArray] : [$day];
}

echo '<pre>';
echo '$finalArray ' . print_r($finalArray, true);
echo '</pre>';
echo '<pre>';
echo '$finalArray json_encoded' . print_r(json_encode($finalArray), true);
echo '</pre>';
exit;

This code will generate a JSON string output like the following:

[  
   [  
      {  
         "opening":"09:30",
         "closing":"13:30",
         "dayName":"sunday"
      }
   ],
   [  
      {  
         "opening":"",
         "closing":"",
         "dayName":"monday"
      },
      [  
         {  
            "from_time":"06:13:16",
            "to_time":"04:14:11",
            "discount":"20",
            "dayName":"monday"
         },
         {  
            "from_time":"06:59:16",
            "to_time":"04:19:11",
            "discount":"20",
            "dayName":"monday"
         }
      ]
   ],
   [  
      {  
         "opening":"",
         "closing":"",
         "dayName":"tuesday"
      },
      [  
         {  
            "from_time":"05:10:15",
            "to_time":"06:10:17",
            "discount":"20",
            "dayName":"tuesday"
         }
      ]
   ],
   [  
      {  
         "opening":"10:30",
         "closing":"06:30",
         "dayName":"wednesday"
      },
      [  
         {  
            "from_time":"13:00:00",
            "to_time":"14:50:00",
            "discount":"20",
            "dayName":"wednesday"
         }
      ]
   ],
   [  
      {  
         "opening":"01:00",
         "closing":"08:00",
         "dayName":"thursday"
      }
   ],
   [  
      {  
         "opening":"",
         "closing":"",
         "dayName":"friday"
      }
   ],
   [  
      {  
         "opening":"",
         "closing":"",
         "dayName":"saturday"
      }
   ]
]

Answer №2

Here is my solution to achieve the desired output:
I have utilized array_combine and array_column functions to create an associative array from the first array.
To merge this with the second array, I loop through it and construct a new array accordingly.

Finally, I use array_values to convert the result into a non-associative array.

foreach($discount as $val){
    $discount2[$val['dayName']][] = $val;
}  

$res = array_values(array_merge_recursive(array_combine(array_column($WH, "dayName"), $WH), $discount2));

var_dump($res);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unchecking random checkboxes within a div using jQuery after checking them all

Once a link is clicked on, all checkboxes within that particular div will be checked. function initSelectAll() { $("form").find("a.selectAll").click(function() { var cb = $(this).closest("div").find("input[type=checkbox]"); cb.not(":checked" ...

Generate a list of JSON strings using a collection of Pydantic objects

I have been working on extracting a list of JSON strings from a collection of Pydantic objects. My current approach involves the following code snippet: raw_books = [json.dumps(x.dict()) for x in batch.books] While this method functions properly, it tends ...

Updating the scope variable in an AngularJS directive

Recently delving into Angular, I encountered an issue: I have both a list view and a details view with tags. To facilitate navigating between the two views and loading new elements from a service upon click events, I created a directive. My aim is to also ...

Create dynamic flex transitions

After searching through various CSS resources and websites, I haven't found an answer to my specific query. I have been exploring CSS tricks as well as http://n12v.com/css-transition-to-from-auto/ but still uncertain if what I'm looking to achiev ...

Debugging an Asterisk AGI file in PHP

Looking for help debugging the AGI script (a2billing.php) in Asterisk. I've been successful when remotely debugging PHP CLI from the Linux console, but it doesn't seem to work when running within Asterisk. Any suggestions on how to properly debu ...

Managing logout feature effectively in Vue.js/LaravelEnsuring proper logout functionality

I'm currently in the process of building a simple SPA with Vue and Laravel. So far, I've managed to set up user registration and login functionalities. However, one thing that's stumping me is how to implement a logout feature. Here's ...

How to Resolve Line Breaks in JSON using PHP

When parsing this JSON array, I need to extract the type object and place it in a new column called type2. However, I am encountering an issue with the foreach() function due to new lines in some of the JSON rows. How can I resolve this? The first row is ...

App Engine serves up JSON data using JsonProperty

I appreciate how the JsonProperty in Python seamlessly encodes data into JSON when saving to the database and decodes it upon retrieval. However, I am seeking a solution to directly send raw JSON data to a web browser without the need for further encodin ...

"Title, background hue 3, and color lined up in a single

.title { background-color: #FFC20E; font-size: 23px; font-weight: 600; padding: 5px 0px 5px 22px; font-family: "Open Sans"; } <h3 class="title">Title</h3> I need to create a title with a unique background color, can you ple ...

Showing data in a grid format on a webpage

I created a Java program that generates an array list with values such as Hi, Hello, How, Are, You, Me, They, and Them. In addition, I developed a basic controller to convert these values into JSON format and display them on localhost:8090/greeting like t ...

invoking a JavaScript function from an HTML file

I want to create a JavaScript server on Raspbian that not only serves .html content to the browser but also allows for user input through events like button clicks. Both my .html and .js files are located in the same directory, and I have used absolute pat ...

I am curious if there is a wysiwyg web editor extension specifically designed for VS2010 available?

In my experience, I have been working with C#, HTML coding using VS2010 and MVC. Utilizing VS2010 has proven to be an invaluable tool for me in this process. Currently, I find myself needing to create some straightforward static web pages. I am wondering ...

angularjs currency conversion tool

Is it possible to choose only 3-4 currency values from a drop-down list, where the selected value will determine the base URL for fetching JSON data? For instance, if I select USD as the first value, the JSON data should be retrieved from . ...

Concealing spinner controls on HTML Ionic number input

Seeking a foolproof method to conceal spinner buttons on an HTML template for Ionic's number input field. Showcased below is the HTML code that exhibits an input with spinner buttons: <ion-input type='number'></ion-input> The ...

Using Ajax with Bootstrap's typeahead feature

I've been struggling to implement typeahead on my website, and here's what I've attempted so far. Here is my HTML and code: <html> <head> <title>typeahead</title> <link href="//maxcdn.bootstrapcdn.com/ ...

Choosing multiple classes using Xpath

<div class="unique"> <a class="nested" href="Another..."><img src="http://..."/></a> <p> different.... </p> <p><img src="http://....." /></p> </div> I have this interesting HTML struc ...

Creating an attention-grabbing alert bar positioned above the menu

When I attempted to add this alert bar to my website, I encountered an issue where it was being hidden behind my menu. Some sources suggest that using z-index and position:absolute can resolve this problem by positioning one element above the other, but th ...

Exploring the depths of JSON nested maps in Groovy: a step-by-step guide

I have received the following JSON output from AWS DynamoDB and I am looking to loop through it in order to populate a table within Jenkins Parameters using a Groovy script. Is this achievable? JSON: [ { "test": { "S ...

Failure to display masonry arrangement

I am working on creating a stunning masonry layout for my webpage using some beautiful images. Take a look at the code snippet below: CSS <style> .masonryImage{float:left;} </style> JavaScript <script src="ht ...

Is Same Origin Policy only enforced in incognito mode while utilizing Ajax?

When I attempt to use ajax to communicate with my server from a device, I encounter an issue. If I access the website in incognito mode, the service fails to work and logs the error message: Cross-Origin Request Blocked: The Same Origin Policy disallows ...