Expected result:
Code: Select all
WORD:SELECT RESULT:2 searched in sql_array
WORD:FROM RESULT:3 searched in sql_array
WORD:LEFT_JOIN RESULT:6 searched in sql_array
WORD:ON RESULT: searched in sql_array
WORD:WHERE RESULT:8 searched in sql_array
SELECT:2
FROM: 3
LEFT_JOIN: 6
ON: 0
WHERE: 8
Code: Select all
generuje tento výstup:
WORD:0 RESULT:0 8 3 6 2 searched in sql_array
--------------
SELECT:0 8 3 6 2
FROM: 0 8 3 6 2
LEFT_JOIN: 0 8 3 6 2
ON: 0 8 3 6 2
WHERE: 0 8 3 6 2
Code: Select all
#!/bin/bash
# My function
search_words() {
local sql_array="$1"
local query="$2"
local words=("${@:3}")
declare -A results=() # Deklaration of ass. arr.
sql_array=$(echo "$sql_array" | sed -e 's/^[ \t]*//') # Trim begin of the lines
# This will create the complete list of words to be found
local all_words=("$query" "${words[@]}")
# This will try to find the word in the text and print the current number where found_
for word in "${all_words[@]}"; do
result=$(echo "$sql_array" | awk -v word="$word" '$0 ~ word {print NR; exit}')
if [ -z "$result" ]; then
result=0
fi
# This should save the number under the word like "SELECT" or "INSERT INTO" if that would be the case, WHERE, FROM etc.
results["$word"]="$result"
done
# This should be hash array passed back to global scope
echo "${results[@]}"
}
clear
# php code - the source of sql_array
sql_array="
'SELECT' => 'f.*',
'FROM' => array(
FORUMS_TABLE => 'f'
),
'LEFT_JOIN' => array(),
'ORDER_BY' => 'f.left_id',
'WHERE' => 'f.id = 1'
"
# I will look for "SELECT" or other query word + "FROM" "LEFT_JOIN" "ON" "WHERE"
words=("FROM" "LEFT_JOIN" "ON" "WHERE")
# The function call
results=$(search_words "$sql_array" "SELECT" "${words[@]}")
# Check this
for word in "${!results[@]}"; do
echo "WORD:$word RESULT:${results[$word]} searched in sql_array"
done
echo "--------------"
# Check this
echo "SELECT:${results[SELECT]}"
echo "FROM: ${results[FROM]}"
echo "LEFT_JOIN: ${results[LEFT_JOIN]}"
echo "ON: ${results[ON]}"
echo "WHERE: ${results[WHERE]}"
Code: Select all
read -p "WORD:$word RESULT:$result searched in sql_array"
Code: Select all
if [ -z "$result" ]; then
Code: Select all
WORD:SELECT RESULT:2 searched in sql_array
WORD:FROM RESULT:3 searched in sql_array
WORD:LEFT_JOIN RESULT:6 searched in sql_array
WORD:ON RESULT: searched in sql_array
WORD:WHERE RESULT:8 searched in sql_array
WORD:0 RESULT:0 8 3 6 2 searched in sql_array