Функция не будет запускаться дважды внутри оператора if if - PullRequest
0 голосов
/ 06 мая 2019

Я хотел бы сделать поиск штрих-кода.

При первой попытке штрих-код просматривается локально по штрих-кодам пользователей.

Если дубликат, функция возвращает первый экземпляр с текстом «найдено локально»

Если штрих-код не найден локально, он должен выполнить глобальный поиск.

Проблема, с которой я столкнулся, связана с оператором if else, когда штрих-код не найден локально.

Следует проверить, найдено ли оно глобально, если оно не найдено локально.

public function updatePricelist(Request $request)
    {

        $user_id = Auth::user()->id;

        $counter = count($_POST["product_name"]);

        //product barcode
        for ($x = 0; $x < $counter; $x++) {
            $product_barcode[] = $_POST["product_barcode"][$x];
        }

        //check the barcode locally
        $result = $this->barcodeLookUp($product_barcode, 'local');

        if (!empty($result)) {

           $result =  "found locally";
        }

        else {

            $result = $this->barcodeLookUp($product_barcode, 'global');

            if (!empty($result)) {

                $result =  "found globally";
            }
        }

        return $result;
    }

    public function barcodeLookUp($product_barcode, $type)
    {

        $user_id = Auth::user()->id;

if ($type === 'local') {

            $db_barcodes = $this->getBarcodes($user_id, 'local');
        }

        if ($type === 'global') {

            $db_barcodes = $this->getBarcodes($user_id, 'global');
        }

        //merge arrays
        $merge_array = array_merge($db_barcodes, $product_barcode);

        function array_dup($ar)
        {
            return array_unique(array_diff_assoc($ar, array_unique($ar)));
        }

        $result = array_dup($merge_array);

        return current($result);

    }

    public function getBarcodes($user_id, $type)
    {


        if ($type === 'local') {

            $result = DB::select('SELECT products FROM vendor_pricelist WHERE user_id = ?', [$user_id]);
        }

        if ($type === 'global') {

            $result = DB::select('SELECT products FROM vendor_pricelist WHERE user_id != ?', [$user_id]);
        }

        $count_results = count($result);

        $temp = [];
        $temp_2 = [];

        for ($x = 0; $x < $count_results; $x++) {

            array_push($temp, json_decode($result[$x]->products));
        }

        $x = 0;

        while ($x < $count_results) {

            foreach ($temp[$x] as $value) {

                array_push($temp_2, $value[2]);
            }

            $x++;
        }

        $result = $temp_2;

        return $result;
    }

Ответы [ 2 ]

1 голос
/ 06 мая 2019

надеюсь, ты в порядке. С вашими ответами Http Laravel пытается преобразовать все ответы в строку или объект, и кажется, что если ваш поиск не возвращает значение, Laravel установит $ result = false (логическое значение), и это даст вам ошибку.

Я переместил некоторый код, чтобы прояснить ситуацию. Во-первых, я добавил оператор else if в вашу функцию updatePricelist () для окончательной проверки. Это должно установить переменную $ result в строку, если поиск не возвращает никаких результатов.

$result = $this->barcodeLookUp($product_barcode, 'global');

    if (!empty($result)) {

        $result = $result." found globally";
    }
    else {
        return "can save to db"; -> //this is to prevent the boolean response
    }

После этого. Я переместил вашу функцию array_dup () за пределы функции barcodeLookUp ().

public function barcodeLookUp($product_barcode, $type)
{

    $user_id = Auth::user()->id;

    if ($type === 'local') {

        $db_barcodes = $this->getBarcodes($user_id, 'local');
    }

    if ($type === 'global') {

        $db_barcodes = $this->getBarcodes($user_id, 'global');
    }

    //merge arrays
    $merge_array = array_merge($db_barcodes, $product_barcode);


    $result = $this->array_dup($merge_array);

    return current($result);

}

public function array_dup($ar)
{
    return array_unique(array_diff_assoc($ar, array_unique($ar)));
}
0 голосов
/ 06 мая 2019

Надеюсь, у вас все хорошо, это может помочь

    //check the barcode locally
    $result = $this->barcodeLookUp($product_barcode, 'local');

    if (empty($result)) {
        $result = $this->barcodeLookUp($product_barcode, 'global');

        if (!empty($result)) {
            return [
                "message" => "found globally",
                "result"  => $result,
            ];
        }

        return [
            "message" => "not found",
            "result"  => null,
        ];
    } else {
        return [
            "message" => "found locally",
            "result"  => $result,
        ];
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...