I am interested in retrieving all the names from table A that are linked to table B

When using Laravel, I am familiar with establishing a relationship between the child and parent tables. This allows me to easily determine how many times the parent is utilizing the child.

In Laravel, I can achieve this by accessing the ID of the parent through the child model like so: $child->parent->id;

However, when it comes to pure PHP, I'm not quite sure how to replicate this functionality. Here's what I have attempted so far:


foreach ($shops as $shop) {
    foreach ($shopAssistants as $shopAS) {
        if($shopAS['shop_id'] != $shop['id']){
            echo '<option id="' . $shop['id'] . '">' . $shop['shop_name'] . '</option>';
        }
    }
}

Answer №1

Condense one of the arrays

 $shopIds  = array_column($shops, 'id');

 foreach ($shopAssistants as $shopAS) {
      if(in_array($shopAS['shop_id'],$shopIds){
 ?> 
 <option id = "<?php echo $shop['id']; ?>"><?php echo $shop['shop_name']; ?> 
 </option>
 }

When using array_column, you are extracting just a single column from a multidimensional array. So if your original array looks like this:

$shops = [ 
   ['id' => 1, 'name' => 'foo'],
   ['id' => 2, 'name' => 'foo'],
   ['id' => 3, 'name' => 'foo'],
]

After applying array_column($shops, 'id'), the result would be:

[1,2,3]

This simplifies the data structure, allowing you to use in_array without the need for two loops.

-Please Note-

If shops is an object, you can convert it into an array like so:

$shopIds  = array_column((array)$shops, 'id');

Make sure that the property id is public in the object.

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

Decipher the JSON code to modify the data

I have a JSON array below. {"entries":[{"uid":155551338258538,"photo":"https:\/\/m.ak.fbcdn.net\/profile.ak\/hprofile-ak-prn1\/323887_155551338258538_1152153357_q.jpg","type":"user","text":"shikhadamodar","path":"\/shikha.dam ...

Guide on automatically attaching a file to an input file type field from a database

Currently, I am implementing a PHP file attachment feature to upload files. Upon successful upload, the system stores the filename with its respective extension in the database. The issue arises when trying to retrieve and display all entries from the ...

Generating a JSON object that includes arrays and defining key-value pairs

My PHP is producing a JSON output with three arrays: eventIDs, TipsTB, and TipsTW. When I pass this JSON to my HTML file, the array values are displayed with keys 0 and 1. How can I assign unique keys like tip1 and tip2? I am creating the array and encodi ...

Passing Node.js MySQL query results to the next function within an async.waterfall workflow

In my node.js code using express, I have set up a route to request data from a mysql database. My goal is to pass the returned JSON in tabular form to another function to restructure it into a hierarchy type JSON. I have individually tested the script to ...

What is the correct way to utilize deleteMany() in the MongoDB shell when using an $and query?

I need to remove all entries in the infrastructure collection with a type.primary of "pipelines" and a type.secondary of "oil." Currently, I'm using this query: db.infrastructure.deleteMany({$and: [{"properties.type.primary": "pipeline ...

Strategies for organizing an array of Imperial measurements (including inches and fractions)

Currently, I have implemented a PHP code snippet to sort values using the native sort algorithm. usort($this->_items, function($a, $b) { return strnatcasecmp($a['label'], $b['label']);}); However, there seems to be an issue with so ...

What could be the reason my foreach loop is not being run?

After creating a login form that successfully grants access upon entering the correct email and password, there seems to be an issue. A foreach loop is implemented to test all results, with the assumption of only one account existing. foreach ($result as ...

Unable to retrieve POST data using AJAX

My goal is to send jQuery variables to a PHP script using Ajax post, but I'm having trouble setting the PHP variables to contain the values of the jQuery variables. I've experimented with different types of Ajax data, such as forms (new FormData ...

Obtaining a date and time in PHP from a JavaScript array

I am currently working on implementing a JQuery datetime picker and my goal is to save the selected date and time into a PHP variable for storage in a MySQL database. Despite browsing through various examples, none of them seem to be effective in achieving ...

Retrieve column names from a table that match a specific pattern by utilizing a query with PDO

Is there a way to retrieve the names of all columns that follow a specific pattern? For instance, retrieving all columns that begin with 'allow'. I prefer to achieve this using only a pure PDO query rather than relying on a PHP array filter. $qu ...

Converting an HTML table into a visual image

I've encountered an issue. My task involves transferring an HTML table to a PDF using fpdf. Is there a way to transform an HTML table into an image (via URL link)? ...

Receiving JSON output twice

I am currently working with CodeIgniter and facing an issue with my form fields, which are Employee_name, fromDate, and endDate. I am using AJAX to send this data without sharing the actual code. The problem arises when retrieving and displaying records fr ...

Arranging a multidimensional array based on key value pairs in PHP

My array contains states with key-value pairs representing companies. I need to sort the array for each state in descending order based on the company's value, with the highest value company listed first and the lowest value company listed last. arr ...

Exploring the capabilities of JSONmodel by attempting to retrieve data from a server onto an iOS device

I've been working on integrating JSONmodel to retrieve data from my server to my iOS device. I have set up all the classes properly, but for some reason, it returns null after calling the URL. feed = [[Feeds alloc] initFromURLWithString:@"http://http ...

Script using PHP to remotely connect to a Linux server and run a Bash script

Currently, I am facing a challenge where I need to execute shell commands on our remote servers using PHP. The main goal is to install scripts through bash by having PHP execute these scripts on the server remotely. However, I have encountered an issue wh ...

The data in my MySQL table is not appearing on an Angular Material table when using Node.js

HTML file content <table mat-table [dataSource]="dataSource" class="mat-elevation-z8"> <ng-container matColumnDef="id"> <th mat-header-cell *matHeaderCellDef> No. </th> <td mat-cell *matCellDef="let element"> {{ele ...

Is AJAX not submitting properly?

Here is the code snippet that I am working with: var just = $("#just").val(); var id = $("#id").val(); $.ajax({ type: "POST", url: "cod_ajax/just.php", data: "id="+id+"&just="+just, cache: false, success:function(e){ aler ...

Only 50% of the time does jQuery actually work

My webpage features two interactive buttons, the "liked" and "disliked" options. These buttons are represented by images attached to a link tag that triggers a database query when clicked. The outcome of this action is displayed in a #Messages section whic ...

Is it possible for PHPUnit to automatically reattempt failed tests multiple times?

I am facing a challenge with my PHPUnit tests, which involve connecting to servers worldwide that occasionally experience timeouts. Instead of failing the test immediately upon server timeout, I would like to have the option to retry the test multiple tim ...

utilizing an ajax request to clear the contents of the div

When I click on Link1 Button, I want to use ajax to empty the contents in the products_list div <button type="w3-button">Link1</button> I need help with creating an ajax call that will clear the products in the product_list when the link1 but ...