Skip to content

Instantly share code, notes, and snippets.

@grzegorz-rozycki
Last active April 17, 2024 08:06
Show Gist options
  • Save grzegorz-rozycki/8e1d5d777659e2ea3db10b151372b796 to your computer and use it in GitHub Desktop.
Save grzegorz-rozycki/8e1d5d777659e2ea3db10b151372b796 to your computer and use it in GitHub Desktop.
A PhpStorm Data Extractor Script for exporting query results into a PHP array.
/*
* Extracts query results as PHP array.
* Tested against PhpStorm 2017.1.3
* Put the file under following path:
* ${HOME}/.PhpStorm2017.1/config/extensions/com.intellij.database/data/extractors
*/
SEPARATOR = ","
QUOTE = "\""
NEWLINE = System.getProperty("line.separator")
def isNumeric = { str ->
try {
double num = Double.parseDouble(str)
return true
} catch (NumberFormatException e) {
return false
}
}
def printRow = { id, keys, values ->
OUT.append(" " + (!isNumeric("" + id) ? (QUOTE + id + QUOTE) : id) + " => [ ")
values.eachWithIndex { value, idx ->
def k = "" + keys.get(idx)
if (!isNumeric(k)) {
OUT.append(QUOTE + k + QUOTE + " => ")
} else {
OUT.append(k + " => ")
}
if (isNumeric("" + value)) {
OUT.append(value)
} else if (value == "NULL") {
OUT.append("null")
} else {
OUT.append(QUOTE + value.replace(QUOTE, "\\" + QUOTE) + QUOTE)
}
OUT.append(idx != values.size() - 1 ? SEPARATOR + " " : "")
}
OUT.append(" ]," + NEWLINE)
}
def columnKeys;
def rowKeys;
def rows = new ArrayList<ArrayList<String>>();
if (!TRANSPOSED) {
ROWS.eachWithIndex { row, index ->
rows.putAt(index, new ArrayList<String>())
COLUMNS.each { column -> rows.getAt(index).push(FORMATTER.format(row, column))}
}
columnKeys = COLUMNS.collect { it.name() }
rowKeys = 0..<rows.size()
} else {
def rowCount = 0
COLUMNS.eachWithIndex { column, index -> rows.putAt(index, new ArrayList<String>()) }
ROWS.each { row ->
COLUMNS.eachWithIndex { column, index -> rows.getAt(index).push(FORMATTER.format(row, column)) }
rowCount++
}
columnKeys = 0..<rowCount
rowKeys = COLUMNS.collect { it.name() }
}
OUT.append("\$rows = [" + NEWLINE)
rowKeys.eachWithIndex { rowKey, index -> printRow(rowKey, columnKeys, rows.get(index)) }
OUT.append("];" + NEWLINE)
@SteenSchutt
Copy link

This is a hidden gem. I was so tired of extracting as JSON, decoding it in PHP and then using print_r or similar to get it out in a vaguely array-like structure. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment