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

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

问题描述:

I need some help. I need to insert the the value if its present inside the user input array using PHP and MySQL. I am explaining my table below.

db_images:

id         image     subcat_id

Here I need to insert into above table as the following json array value.

$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 (i.e-$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 . Please help.

我需要一些帮助。 我需要使用PHP和MySQL在用户输入数组中插入值。 我正在解释下面的表格。 p>

db_images: p> blockquote>

  id image subcat_id 
   code>  pre> 
 
 

这里我需要在上面的表中插入以下json数组值。 p>

  $ subcat = array(array  ( “ID”=> 63),阵列( “ID”=> 64)); 
 $的imageArr =阵列(阵列( “图像”=> “中abc.png”, “ID”=> 63  )); 
  code>  pre> 
 
 

这里我需要匹配两个数组,如果 $ subcat code>数组中的任何值存在于第二个数组内( ie- $ imageArr code>)数组然后将相关图像插入到表中,如果不存在,则空白图像值将插入相应的 subcat_id code>。 请帮忙。 p> div>

For every element in the subcat array, you can iterate on the imageArr and check if the ids match (nested loop), like this:

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.

<?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>';
    }
}