Fast access to models in a ArrayDataProvider based on their key?

28 Views Asked by At

I have an ArrayDataProvider of Items, returned by a function of the following form:

public function builder() {
  $items = Item::find()->all();
  $dataProvider = new ArrayDataProvider([
     'allModels'  => $items,
     'pagination' => false,
     'id'         => 'items_dp'
  ]);
  return $dataProvider;
}

For various reasons, I need the code for this function to stay as it is.

My question is, if I have a list of Item ids, myItemIds, is there any way to rapidly select Items in the DataProvider having those ids one by one? For example, in an application like:

$provider = builder();
$myItemIds = [112,321,422];
$superItems = [];
foreach ($myItemIds->each() as $itemId) {
  $superItem = // builder based on data from the Item in DataProvider with id = $itemId and other things;
  $superItems[] = $superItem;
}
1

There are 1 best solutions below

2
Jaydeep Khokhar On

Given your scenario and the constraint of keeping the builder function as is, to select Items in the ArrayDataProvider with specific IDs ($myItemIds), you would need to iterate through the data provider's models and check if an item's ID is in your list of IDs. Here is an example of how you could achieve this:

$provider = builder(); // Assuming this calls your builder function and returns an ArrayDataProvider
$myItemIds = [112, 321, 422];
$superItems = [];

// Get all models from the provider
$allModels = $provider->allModels;

// Iterate through the list of IDs you want to find
foreach ($myItemIds as $itemId) {
    // Search for the item by ID in the array of all models
    $key = array_search($itemId, array_column($allModels, 'id'));
    if ($key !== false) {
        // If the item is found, you can process it as needed
        $item = $allModels[$key];
        // Assuming you have some logic to build a "super item" from an item
        $superItem = // Your logic to transform $item into $superItem goes here;
        $superItems[] = $superItem;
    }
}

// Now $superItems contains your processed items

This code snippet assumes that $allModels contains an array of objects where each object has an id property that you can compare against your list of desired item IDs ($myItemIds). The array_search function is used in conjunction with array_column to find the index of each item by ID in the array of all models. Once an item is found, you can then process it according to your needs and add the result to the $superItems array.

Note: This approach assumes that the id field is directly accessible on your item objects and that $allModels is a simple array of objects. If your actual data structure is different, you may need to adjust the search logic accordingly.