Создание таблицы с функцией php, но с некоторыми проблемами - PullRequest
0 голосов
/ 19 декабря 2018

Итак, мне помогли правильно заполнить данные, но при попытке создать таблицу я не могу заставить ее работать должным образом.Я посмотрел в Интернете и не могу найти решение, может быть, я просто пропустил его.

Это код, который я хочу изменить

function getplayers()
{
$json = file_get_contents('http://116.203.39.175:30120/players.json');

$json_data = json_decode($json, true);

foreach ($json_data as $player_data) {
    // Initialise the steam id to an empty string in case one is not found
    $player_steam_id = "";
    $player_lic = "";
    // Find the steam id in the identifiers array
    if (array_key_exists("identifiers", $player_data)) {
        $steam_identifiers = [];
        foreach ($player_data["identifiers"] as $identifier_str)
            if (preg_match("/^steam:/i", $identifier_str, $m))
                $steam_identifiers[] = $identifier_str;
        if (!empty($steam_identifiers)) {
            $player_steam_id = $steam_identifiers[0];
        }
    }
    if (array_key_exists("identifiers", $player_data)) {
        $steam_identifiers = [];
        foreach ($player_data["identifiers"] as $identifier_str)
            if (preg_match("/^license:/i", $identifier_str, $m))
                $steam_identifiers[] = $identifier_str;
        if (!empty($steam_identifiers)) {
            $player_lic = $steam_identifiers[0];
        }
    }
    $player_id = $player_data["id"];
    $player_name = $player_data["name"];


    echo '
        <table id="allUsers" class="table table-striped table-bordered">
        <thead>
            <tr>
            <th>Player ID</th>
            <th>Name</th>
            <th>Steam ID</th>
            <th>License</th>
            <th>Actions</th>
            </tr>
        </thead>
        <tbody>
    ';

        echo '
        <tr>
            <td>' . $player_id . '</td>
            <td>' . $player_name . '</td>
            <td>' . $player_steam_id . '</td>
            <td>' . $player_lic . '</td>
            <td>
                <input name="deleteBan" type="submit" class="btn btn-xs btn-link" onclick="deleteBan(' . $player_id . ')" value="Delete" />
                ';

        echo '

                <input name="bid" type="hidden" value=' . $player_id . ' />
                </form>
            </td>
        </tr>
        ';


    echo '
        </tbody>
        </table>
    ';
}}

Новый код с Json

, и этот код работает аналогично SQL, ноЯ не уверен, как получить ту же конечную точку.

function getbans()
{
    $link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, "mayfairg_fivem");
    $site = BASE_URL;
    if (!$link)
    {
        die('Could not connect: ' . mysql_error());
    }

    $query = "SELECT id,identifier,license,targetplayername,sourceplayername,reason,added,
    case 
    when permanent = 1 then 'Yes'
    when permanent = 0 then 'No'
    end
    FROM banlist";

    $result = mysqli_query($link, $query);

    echo '
        <table id="allUsers" class="table table-striped table-bordered">
        <thead>
            <tr>
            <th>Steam ID</th>
            <th>License</th>
            <th>Banned Player</th>
            <th>Admin</th>
            <th>Reason</th>
            <th>Date</th>
            <th>Perm?</th>
            <th>Actions</th>
            </tr>
        </thead>
        <tbody>
    ';

    while ($row = mysqli_fetch_array($result, MYSQLI_BOTH))
    {
        echo '
        <tr>
            <td>' . $row[1] . '</td>
            <td>' . $row[2] . '</td>
            <td>' . $row[3] . '</td>
            <td>' . $row[4] . '</td>
            <td>' . $row[5] . '</td>
            <td>' . $row[6] . '</td>
            <td>' . $row[7] . '</td>
            <td>
                <form action="'.$site.'/actions/adminActions.php" method="post">
                <input name="deleteBan" type="submit" class="btn btn-xs btn-link" onclick="deleteBan(' . $row[0] . ')" value="Delete" />
                ';

        echo '

                <input name="bid" type="hidden" value=' . $row[0] . ' />
                </form>
            </td>
        </tr>
        ';
    }

    echo '
        </tbody>
        </table>
    ';

}

Работа с SQL

Ответы [ 2 ]

0 голосов
/ 19 декабря 2018

Вот некоторая очистка кода для вас.break в вашем внутреннем цикле - лучший способ избежать лишних итераций.Ваши preg_match() вызовы могут быть объединены в один для генерации назначения массива переменных.Я использую оператор объединения нулей, чтобы объявить пустую строку в качестве запасного варианта для пропущенных идентификаторов.

Код: ( Демо )

$players = json_decode($json, true);
foreach ($players as $player) {
    if (!empty($player['identifiers'])) {
        foreach ($player["identifiers"] as $id) {
            if (preg_match("/^(steam|license):([a-f\d]+)$/", $id, $m)) { // target the two specific ids
                $player[$m[1]] = $m[2];
            }
            if (isset($player['steam'], $player['license'])) {
                break;  // stop iterating, we have everything we want
            }
        }
    }
    $player['steam'] ?? '';  // fallback to empty string when not found
    $player['license'] ?? '';  // fallback to empty string when not found

    echo '
        <tr>
            <td>' . $player["id"] . '</td>
            <td>' . $player["name"] . '</td>
            <td>' . $player["steam"] . '</td>
            <td>' . $player["license"] . '</td>
            <td>
                <input name="deleteBan" type="submit" class="btn btn-xs btn-link" onclick="deleteBan(' . $player["id"] . ')" value="Delete" />
        </tr>
    ';
}
0 голосов
/ 19 декабря 2018

Я понял, что это было простое исправление, у меня было "}" в неправильном месте.

function getplayers()
{
        echo '
        <table id="allUsers" class="table table-striped table-bordered">
        <thead>
            <tr>
            <th>Player ID</th>
            <th>Name</th>
            <th>Steam ID</th>
            <th>License</th>
            <th>Actions</th>
            </tr>
        </thead>
        <tbody>
    ';
$json = file_get_contents('http://116.203.39.175:30120/players.json');

$json_data = json_decode($json, true);

foreach ($json_data as $player_data) {
    // Initialise the steam id to an empty string in case one is not found
    $player_steam_id = "";
    $player_lic = "";
    // Find the steam id in the identifiers array
    if (array_key_exists("identifiers", $player_data)) {
        $steam_identifiers = [];
        foreach ($player_data["identifiers"] as $identifier_str)
            if (preg_match("/^steam:/i", $identifier_str, $m))
                $steam_identifiers[] = $identifier_str;
        if (!empty($steam_identifiers)) {
            $player_steam_id = $steam_identifiers[0];
        }
    }
    if (array_key_exists("identifiers", $player_data)) {
        $steam_identifiers = [];
        foreach ($player_data["identifiers"] as $identifier_str)
            if (preg_match("/^license:/i", $identifier_str, $m))
                $steam_identifiers[] = $identifier_str;
        if (!empty($steam_identifiers)) {
            $player_lic = $steam_identifiers[0];
        }
    }
    $player_id = $player_data["id"];
    $player_name = $player_data["name"];
   

        echo '
        <tr>
            <td>' . $player_id . '</td>
            <td>' . $player_name . '</td>
            <td>' . $player_steam_id . '</td>
            <td>' . $player_lic . '</td>
            <td>
                <input name="deleteBan" type="submit" class="btn btn-xs btn-link" onclick="deleteBan(' . $player_id . ')" value="Delete" />
                ';
       
        echo '

                <input name="bid" type="hidden" value=' . $player_id . ' />
                </form>
            </td>
        </tr>
        ';
}

    echo '
        </tbody>
        </table>
    ';
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...