Reputation: 144
I want to create an if statement dynamically in PHP, but I don't know how to do this. For example, I am creating an Excel with different heights, widths and prices.
If my valueWidth < width the price is equal to the width price above.
If my width = 2050 and height = 2560, the prices is 621$.
The width, height and prices is entered dynamically and can be different from 3 numbers. Width, height and prices is Array.
width = [2000,3025,4036]
height = [2214,2411,2608]
class_1 = [245,272,302]
class_2 = [537,584,621]
class_3 = [755,799,836]
class_X = [...]
Can you help me find how to do the conditions effectively, please ?
Upvotes: 0
Views: 50
Reputation: 2644
You may be aware of associative arrays, where you have a named key and a value:
$data = array('keyName' => 'value');
print $data['keyName'];
// ==> 'value'
But for a grid, you need two indexes:
$grid = array(
'rowName' => array(
'colName' => 'rowColValue'
)
);
print $grid['rowName']['colName'];
// == 'rowColValue'
So to condense all your data into one place, it would look like this:
$grid['2000']['2214'] = 245;
$grid['2000']['2411'] = 272;
$grid['2000']['2680'] = 302;
$grid['3025']['2214'] = 537;
$grid['3025']['2411'] = 584;
$grid['3025']['2086'] = 621;
$grid['4036']['2214'] = 755;
$grid['4036']['2411'] = 799;
$grid['4036']['2680'] = 836;
$width = '3025';
$height = '2411';
print $grid[$width][$height];
//==> 584
Assignment is just as easy as getting the results:
// assume $width. $height, and $price are user input, properly validated
$grid[$width][$height] = $price;
Alternately, if you need to build this from the arrays you supplied:
width = [2000,3025,4036]
height = [2214,2411,2608]
class_1 = [245,272,302]
class_2 = [537,584,621]
class_3 = [755,799,836]
class_X = [...]
Build a nested loop something like this:
$prices = [];
$prices[] = $class_1;
$prices[] = $class_2;
$prices[] = $class_3;
// etc.
$grid = [];
$classNumber = 0;
foreach($width as $w) {
foreach($height as $h) {
$grid[$w][$h] = $prices[$classNumber];
}
$classNumber++;
}
Upvotes: 2