简体   繁体   English

如何检查数组中是否存在值,以及如何使用PHP将值插入数据库

[英]How to check the value is present inside an array and insert the value into database using PHP

I need some help. 我需要协助。 I need to insert the the value if its present inside the user input array using PHP and MySQL. 我需要使用PHP和MySQL将值(如果它存在于用户输入数组中)插入。 I am explaining my table below. 我正在解释下面的表格。

db_images: db_images:

id         image     subcat_id

Here I need to insert into above table as the following json array value. 在这里,我需要作为以下json数组值插入到上表中。

$subcat=array(array("id"=>63),array("id"=>64));
$imageArr=array(array("image"=>"abc.png","id"=>63));

Here I need to match both array if any value from $subcat array is present inside the second ( ie-$imageArr ) array then the resepective image will insert into the table and if not present the the blank image value will insert with the respective subcat_id . 如果在第二个数组( ie-$imageArr )内存在$subcat数组中的任何值,那么我需要匹配两个数组,然后将分别插入相应的图像,如果不存在,则空白图像值将与相应的subcat_id插入。 Please help. 请帮忙。

For every element in the subcat array, you can iterate on the imageArr and check if the ids match (nested loop), like this: 对于subcat数组中的每个元素,您可以迭代imageArr并检查id是否匹配(嵌套循环),如下所示:

foreach($subcat as $s) {
    $flag = false;

    foreach($imageArr as $i) {
        if ($s['id'] == $i['id']) {
            // insert ($i['image'], $s['id']) into db
            $flag = true;
            break;
        } 
    }

    if ($flag == false) {
        // insert $s['id'] into db
    }
}

Hi you can even do in the following way with the help of array_column and in_array with loop reduced. 嗨,您甚至可以在array_columnin_array减少循环的帮助下以以下方式进行操作。

<?php

$subcat=array(array("id"=>63),array("id"=>64));
$imageArr=array(array("image"=>"abc.png","id"=>63), array("image"=>"abc.png","id"=>65));

foreach($imageArr as $image){
    /* array_column will do the job with in_array to search in the multi dimension array */
    if(in_array($image['id'], array_column($subcat, 'id'))){
        echo 'exists'. $image['id'].'<br>'; 
    }else{
        echo 'not exists'. $image['id'].'<br>';
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM