我有一个看起来像这样的PHP数组...
array
(
[0] => apple,
[1] => orange,
[2} => ,
[3] => ,
)
我需要确保数组包含4个项目,因此在上面的实例中,我想以此结束...
# Utility function to convert string to list
def toMutable(string):
temp = []
for x in string:
temp.append(x)
return temp
# Utility function to convert string to list
def toString(List):
return ''.join(List)
# Function to remove duplicates in a sorted array
def removeDupsSorted(List):
res_ind = 1
ip_ind = 1
# In place removal of duplicate characters
while ip_ind != len(List):
if List[ip_ind] != List[ip_ind-1]:
List[res_ind] = List[ip_ind]
res_ind += 1
ip_ind+=1
# After above step string is efgkorskkorss.
# Removing extra kkorss after string
string = toString(List[0:res_ind])
return string
# Function removes duplicate characters from the string
# This function work in-place and fills null characters
# in the extra space left
def removeDups(string):
# Convert string to list
List = toMutable(string)
# Sort the character list
List.sort()
# Remove duplicates from sorted
return removeDupsSorted(List)
# Driver program to test the above functions
string = "geeksforgeeks"
print removeDups(string)
我最好用一个计数器循环遍历并创建一个新数组,还是有更好的方法?
答案 0 :(得分:6)
strtol()包含所需大小的元素的数组:
$my_arr = [1,2];
$my_arr = array_pad($my_arr, 4, '');
答案 1 :(得分:1)
这应该做你想做的
$iNumberOfElements = 5;
$a = array('apple', 'orange');
if(count($a) < $iNumberOfElements){
while (count($a) < $iNumberOfElements) {
$a[] = "";
}
}
var_dump($a);
exit;
答案 2 :(得分:1)
@iainn所说:php.net/manual/en/function.array-pad.php
有这个功能:
$input = array(12, 10, 9);
$result = array_pad($input, 5, 0);
// result is array(12, 10, 9, 0, 0)
5是数组的大小,0是空单元格的默认值