PHP logic problem

Asked

Viewed 110 times

1

I have the following structure in PHP:

<?php
header('Content-Type: application/json; charset=utf-8');

error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE | E_STRICT);
ini_set('display_errors', 'On');

$idplan = ( empty($_POST['idplano']) ? "" : $_POST['idplano'] );
$method = ( empty($_POST['metodo']) ? "" : $_POST['metodo'] );

if ( empty($idplan) || empty($method) ) {
    http_response_code(401);
    die('{"msg": "Plano ou Método não informado."}');
}

$plans_available = array(
    array( 
        "plan" => 22, 
        "allowed_methods" => array(
            "creditcard",
            "giftcard"
        ), 
        "modality" => "mensal"
    ),
    array( 
        "plan" => 23, 
        "allowed_methods" => array(
            "creditcard"
        ),
        "modality" => "mensal"
    ),
    array( 
        "plan" => 30, 
        "allowed_methods" => array(
            "boleto"
        ),
        "modality" => "trimestral" 
    ),
    array( 
        "plan" => 31, 
        "allowed_methods" => array(
            "boleto"
        ),
        "modality" => "semestral" 
    ),
    array( 
        "plan" => 32, 
        "allowed_methods" => array(
            "boleto"
        ),
        "modality" => "anual" 
    ),
    array( 
        "plan" => 33, 
        "allowed_methods" => array(
            "boleto"
        ),
        "modality" => "trimestral" 
    ),
    array( 
        "plan" => 34, 
        "allowed_methods" => array(
            "boleto"
        ),
        "modality" => "semestral" 
    ),
    array( 
        "plan" => 35, 
        "allowed_methods" => array(
            "boleto"
        ),
        "modality" => "anual" 
    )
);

$found = 0;
for($i = 0; $i < count($plans_available); $i++){
    // Teste condicional
    if ($plans_available[$i]["plan"] == $idplan && in_array($method, $plans_available[$i]["allowed_methods"])){
        $found = 1;
    }
}
if(!$found){
    http_response_code(401);
    die('{"msg": "Plano não encontrado."}');
}
die("encontrado!");
?>

I tried to create a logic that would verify the following:

If the modality is reported, it should be tested to match the reported plan, but only test the plan and permitted methods.

However I caught on to that check, in the above code I do not check the mode, and it works!


I tried something like:

if ( $plans_available[$i]["plan"] == $idplan && in_array($method, $plans_available[$i]["allowed_methods"]) && empty($modality) ){
    $found = 1;
} else if ( $plans_available[$i]["plan"] == $idplan && in_array($method, $plans_available[$i]["allowed_methods"]) && $plans_available[$i]["modality"] == $modality ){
    $found = 1;
}

It just doesn’t match what I need.

  • It doesn’t get any simpler $plans = array( '1' => array( "allowed... where the key is the plan id? pq ai vc will simply test in_array( $method, $plans[$plano_informado]['allowed_methods'] )

  • The $modality comes from the POST also?

  • @Bacco I just gave an example, because actually the id of the plan is another :P

  • I edited with an example of the array that more or less matches my reality

2 answers

4

Use the array_filter

With this function you can specify a filter by plan and method and if you do not return any element of the array it is because it does not exist. If you need to know the array items that satisfy the condition, just take the result of the call.

$found = !empty(array_filter($plans_available, function ($i) use ($idplan, $method)  { 
    return key_exists("plan",$i) && 
           key_exists("allowed_methods", $i) && 
           $i["plan"] == $idplan && 
           in_array($method, $i["allowed_methods"]); 
}));

3


You can simply use && (empty($modality) || $plans_available[$key]['modality'] == $modality).

$found = 0;

$get_arr_key = array_search($idplan, array_column($plans_available, 'plan'));

if($get_arr_key !== false
    && in_array($method, $plans_available[$get_arr_key]['allowed_methods'])
    && (empty($modality) || $plans_available[$get_arr_key]['modality'] == $modality)){

    $found = 1;

}

var_dump($found);

/!\ The empty() considers that 0 is emptiness!

Test it out here.

If you want to create functions with slightly more meaningful names, just one example:

$plano_selecionado = getArrayKeyPlano($plans_available, $idplan);

$found = $plano_selecionado !== false
         && isMethodDisponivel($plans_available, $plano_selecionado, $method)
         && isModalityDisponivel($plans_available, $plano_selecionado, $modality);

function getArrayKeyPlano($array, $idPlano){
    return array_search($idPlano, array_column($array, 'plan'));
}

function isMethodDisponivel($array, $array_key, $metodo){
    return in_array($metodo, $array[$array_key]['allowed_methods']);
}

function isModalityDisponivel($array, $array_key, $modalidade){
    return (empty($modalidade) || $array[$array_key]['modality'] == $modalidade);
}

Next to "how are you":

for($i = 0; $i < count($plans_available); $i++){
    if ( $plans_available[$i]["plan"] == $idplan
        && in_array($method, $plans_available[$i]["allowed_methods"])
        && (empty($modality) || $plans_available[$i]['modality'] == $modality) ){

        $found = 1;

    }
}

Test this.

  • I find the last form more lean and simpler rs, but the others can be as an option in case someone someday wants to apply something similar :]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.