John Davidson

php - Efficient way to search array with substring

0 comments
Message:


This is my array.


array (
0 =>
(object) array(
'per_unit_price' => NULL,
'code' => 'dynamic_labour_cost',
'text_value' => '1000',
),
1 =>
(object) array(
'per_unit_price' => NULL,
'code' => 'dynamic_metal_weight',
'text_value' => '10',
),
2 =>
(object) array(
'per_unit_price' => NULL,
'code' => 'dynamic_stone_carat',
'text_value' => '10',
),
3 =>
(object) array(
'per_unit_price' => NULL,
'code' => 'dynamic_stone2_carat',
'text_value' => '10',
),
4 =>
(object) array(
'per_unit_price' => '10.00',
'code' => 'dynamic_metal',
'text_value' => NULL,
),
5 =>
(object) array(
'per_unit_price' => '20.00',
'code' => 'dynamic_stone',
'text_value' => NULL,
),
6 =>
(object) array(
'per_unit_price' => '50.00',
'code' => 'dynamic_stone2',
'text_value' => NULL,
),
)

In short,


Let's take an example =


I want to multiply => array[1]['text_value'] * array[4]['per_unit_price']



Because
array[1]['code'] = dynamic_metal_weight is substring of array[4]['code'] = dynamic_metal


As all code are dynamic so I cannot hard code condition.


And I tried using for each [scan all the array] but It will take a lot of time by traditional loops.


Please guide me.



My Answer:
One efficient way to search for a substring in an array is to use array_filter() function along with a custom callback function. Here's an example code snippet to achieve this:

php
// Your array
$array = [
(object) ['per_unit_price' => NULL, 'code' => 'dynamic_labour_cost', 'text_value' => '1000'],
(object) ['per_unit_price' => NULL, 'code' => 'dynamic_metal_weight', 'text_value' => '10'],
(object) ['per_unit_price' => NULL, 'code' => 'dynamic_stone_carat', 'text_value' => '10'],
(object) ['per_unit_price' => NULL, 'code' => 'dynamic_stone2_carat', 'text_value' => '10'],
(object) ['per_unit_price' => '10.00', 'code' => 'dynamic_metal', 'text_value' => NULL],
(object) ['per_unit_price' => '20.00', 'code' => 'dynamic_stone', 'text_value' => NULL],
(object) ['per_unit_price' => '50.00', 'code' => 'dynamic_stone2', 'text_value' => NULL]
];

// Search for the substring in the array
$searchTerm = 'dynamic_metal';
$filteredArray = array_filter($array, function($item) use ($searchTerm) {
return strpos($item->code, $searchTerm) !== false;
});

// Now you can perform your desired operation on the filtered array
foreach ($filteredArray as $item) {
// Perform your operation here
echo $item->text_value * $item->per_unit_price . "\n";
}


In this code snippet, we use array_filter() to filter out the elements in the array that contain the substring 'dynamic_metal'. Then, we can perform our desired operation on the filtered array. This approach is more efficient than using a traditional loop to scan through the entire array.

Rate this post

3 of 5 based on 6534 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us