PHP: вставить с условием - PullRequest
       2

PHP: вставить с условием

0 голосов
/ 07 апреля 2020

У меня такой запрос:

$content = "How technology is helping to change the way people think about the food on their plate and the food impact for them. Technology could have a role to play in raising awareness of the impact our diets have on the planet.";

$exp = explode(" ", $content)

for($j = 0; $j < count($exp); $j++){
    $this->db->query("INSERT INTO news (news_id, news_content) VALUES ('$id', $exp[$j])");
}

Но я не хочу вставлять все слова, мне просто нужно вставить слово, которое появляется только несколько раз (технология, еда, влияние). Возможно ли это сделать? кто-нибудь может мне помочь?

Ответы [ 2 ]

0 голосов
/ 07 апреля 2020

Я считаю, что здесь много вариантов.

Вот мое решение (я): Вы можете использовать search_array() для этого. Массив поиска возвращает false, если в массиве in_array не найдено никакой другой иглы. Если найдено другое слово, возвращается ключ.

В зависимости от ваших потребностей, вы можете использовать один из следующих вариантов ниже.

//Option 1
//Words that actually appear more than once... 
$new_arr = array();
foreach($exp as $key=>$e) {
    //Must be this word only (therefore the true-statement
    $search = array_search($e, $exp, true); 
    if ($search !== false && $search != $key) {        
        $new_arr[] = $e;
    }
}

//Option 2
//
//Your question was not totally clear so I add this code as well
//Words with asterixes before and after that appear more than once
$new_arr = array();
foreach($exp as $key=>$e) {

    //Two asterixes at the beginning of the sting and two at the end
    //strtolower sets **Technology** and **technology** as a duplicate of word
    if (substr($e,0,2) == "**" && substr($e,-2,2) == "**") { 
        $search = array_search(strtolower($e), $exp);
        if ($search !== false && $search != $key) {        
            $new_arr[] = $e;
        }
    }
}

for($j = 0; $j < count($new_arr); $j++){
    $this->db->query("INSERT INTO news (news_id, news_content) 
    VALUES ('$id', $new_arr[$j])");
}

Как кто-то упоминал в комментарии, вы должны предотвратить SQL инъекции, введя таким образом в INSERT- оператор (и вы должны это сделать), но вопрос был в основном в том, чтобы найти дубликаты в строке и что-то с ними сделать, поэтому я не буду go дальше с этим комментарием.

Массив результатов $new_arr будет например: (вариант 1)

array (size=9)
  0 => string 'the' (length=3)
  1 => string 'the' (length=3)
  2 => string '**food**' (length=8)
  3 => string 'to' (length=2)
  4 => string 'the' (length=3)
  5 => string '**impact**' (length=10)
  6 => string 'have' (length=4)
  7 => string 'on' (length=2)
  8 => string 'the' (length=3)

Причина, по которой Технология и Технология - это не одно и то же, потому что это заглавная буква T в одном из слов.

Массив результатов $new_arr хотел бы: (вариант 2)

array (size=3)
  0 => string '**food**' (length=8)
  1 => string '**Technology**' (length=14)
  2 => string '**impact**' (length=10)
0 голосов
/ 07 апреля 2020

Я бы обработал текстовое содержимое, используя array_filter, чтобы исключить слова из списка стоп-слов, затем посчитал вхождения каждого слова, используя array_count_values, а затем array_filter из слов, которые встречаются только один раз. Затем вы можете записать оставшиеся слова (которые будут ключами выходного массива) в базу данных. Например:

$content = "How technology is helping to change the way people think about the food on their plate and the food impact for them. Technology could have a role to play in raising awareness of the impact our diets have on the planet.";

$stopwords = array('how', 'is', 'to', 'the', 'way', 'on', 'and', 'for', 'a', 'in', 'of', 'our', 'have');

// count all words in $content not in the stopwords list
$counts = array_count_values(array_filter(explode(' ', strtolower($content)), function ($w) use ($stopwords) {
    return !in_array($w, $stopwords);
}));
// filter out words only seen once
$counts = array_filter($counts, function ($v) { return $v > 1; });
// write those words to the database
foreach ($counts as $key => $value) {
    $this->db->query("INSERT INTO news (news_id, news_content) VALUES ('$id', '$key')");
}

Для ваших выборочных данных конечный результат в $counts будет:

Array
(
    [technology] => 2
    [food] => 2
    [impact] => 2
)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...