我正在尝试生成随机字符。我使用foreach循环连接 $ char_type 的值,但它没有显示任何内容。这是我的代码:
TMyDataAwareComponent = class(TDataAwareComponent)
private
{ Private declarations }
procedure ToBeExecutedOnAfterOpen(DataSet: TDataSet);
protected
{ Protected declarations }
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
end;
constructor TMyDataAwareComponent.Create(AOwner: TComponent);
begin
inherited;
if Assigned(Self.DataSource) then
begin
Self.DataSource.DataSet.AfterOpen := ToBeExecutedOnAfterOpen;
end;
end;
procedure TMyDataAwareComponent.ToBeExecutedOnAfterOpen(DataSet: TDataSet);
var
i: Integer;
begin
// Do something here
end;
更新
我想从 public function randomizer($range, $type) {
$strtester = '';
$char_type = array('alp_sm' => 'abcdefghijklmnopqrstuvwxyz',
'alp_cs' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'num' => '0123456789',
'sp' => '!@#$%^&*()');
if(is_array($type)) {
foreach($type as $row) {
if(in_array($row, $char_type)) {
$strtester .= $char_type[$row];
}
}
}
print_r($strtester); exit();
$seed = str_split($strtester);
shuffle($seed);
$generated_string = '';
foreach (array_rand($seed, $range) as $k) $generated_string .= $seed[$k];
return $generated_string;
}
得到的是例如我想要$strtester
alp_sm 和 alp_cs 然后$char_type
将获得{{1} }}
提前谢谢
答案 0 :(得分:3)
将if(in_array($row, $char_type)) {
替换为if(array_key_exists($row, $char_type)) {
,然后尝试
function randomizer($range, $type) {
$strtester = '';
$char_type = array('alp_sm' => 'abcdefghijklmnopqrstuvwxyz',
'alp_cs' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'num' => '0123456789',
'sp' => '!@#$%^&*()');
if(is_array($type)) {
foreach($type as $row) {
if(array_key_exists($row, $char_type)) {
$strtester .= $char_type[$row];
}
}
}
$seed = str_split($strtester);
shuffle($seed);
$generated_string = '';
foreach (array_rand($seed, $range) as $k)
$generated_string .= $seed[$k];
return $generated_string;
}
$res = randomizer(5, array("alp_sm"));
print_r($res);
答案 1 :(得分:1)
错误在于:
if(in_array($row, $char_type)) {
您实际上是在查找密钥是否存在,而不是数组是否包含该字符串 - 您需要使用isset:
if(is_array($type)) {
foreach($type as $row) {
if(isset($char_type[$row]) {
$strtester .= $char_type[$row];
}
}
}
print_r($strtester); exit();
答案 2 :(得分:1)
我不确定这一点,但我认为这可能是最容易解决的问题
function randomizer($range, $type) {
$char_type = array('alp_sm' => range('a','z'),
'alp_cs' => range('A','Z'),
'num' => range(0,9),
'sp' => ['!','@','#','$','%','^','&','*','(',')']);
shuffle($char_type[$type[0]]);
$generated_string = implode(array_slice($char_type[$type[0]],0,$range));
return $generated_string;
}
$res = randomizer(5, array("alp_sm"));
print_r($res);
答案 3 :(得分:0)
您必须检查is_array
。它检查变量是否为数组
$strtester = '';
if(is_array($type)) {
foreach($type as $row) {
if(isset($char_type[$row]) {
$strtester .= $char_type[$row];
}
}
}