0

嘿伙计们,我试图从数据库中获取字符串的偶数索引,然后将它们保存在一个变量中,然后回显。但我的代码似乎不起作用。请帮忙。这里是

require_once('DBconnect.php');
$school_id = '1';
$section_id = '39';
$select_pk = "SELECT * FROM section 
    WHERE school_id = '$school_id' 
    AND section_id = '$section_id'";
$query = mysql_query($select_pk) or die (mysql_error());
while ($row = mysql_fetch_assoc($query)) {
    $public_key = $row['public_key'];
}

if ($public_key) {
    $leng_public_key = strlen($public_key);
    $priv_key_extract = "";
    $array_pki = array();
    for ($i=0; $i <=$leng_public_key-1 ; $i++) { 
        array_push($array_pki,$public_key[$i]);
    }

    foreach ($array_pki as $key  => $value) {
        if($key % 2 == 0) {
            $priv_key_extract += $public_key[$key];
        } else {
            $priv_key_extract ="haiiizzz";
        }
    }
}
echo $priv_key_extract;

正如你所看到的,我试图使用模 2 来查看索引是否是偶数。

4

2 回答 2

1

我已将您的代码更新如下,现在可以使用:

<?php
$public_key = 'A0L8V1I5N9';
if ($public_key) {
    $leng_public_key = strlen($public_key);
    $priv_key_extract = "";
    $array_pki = array();
    for ($i=0; $i <=$leng_public_key-1 ; $i++) {
        array_push($array_pki,$public_key[$i]);
    }
    foreach ($array_pki as $key  => $value) {
        //Changed condition below $key % 2 ==0 => replaced with $key % 2 == 1
        if($key % 2 == 1) {
            // Changed concatenation operator , += replaced with .=
            $priv_key_extract .= $public_key[$key];
        } /*else {
            //Commented this as it is getting overwritten
            $priv_key_extract ="haiiizzz";
        }*/
    }
}
echo $priv_key_extract;
?>
于 2013-02-19T04:31:22.450 回答
0

试试这个功能

function extractKey($key) {
    if (empty($key) || !is_string($key)) return '';

    $pkey = '';
    for ($i=0;$i<strlen($key);$i++) {
        if ($i % 2 == 0) {
            $pkey .= $key[$i];
        }
    }
    return $pkey;
}
echo extractKey('12345678'); # => 1357
于 2013-02-19T04:42:45.130 回答