如何添加静态值作为数组的第一个元素或开始?数组的数据来自我的数据库。
下面我试图在前面添加"选择样式",但不是,它只是将我的第一个元素进行梳理。
$query = "SELECT DISTINCT name FROM ImageInfo";
$db = new connection();
$result = $db->query($query);
while($info = mysql_fetch_array($result)){
$content[] = $info;
}
$result=array();
$count = count($content);
$result[0][] = "Select Style";
for ($x=0;$x<$count;++$x)
{
$result[$x][] = $content[$x]['name'];
}
echo json_encode($result);
您的问题似乎是以下几行
$result[0][] = "Select Style";
和
$result[$x][] = $content[$x]['name'];
你将数组中的第一个值设置为"Select Style"然后在for循环的第一次迭代中你有$x == 0所以它会覆盖你在
中输入的值你可以修改
$result[$x][] = $content[$x]['name'];
$result[][] = $content[$x]['name'];
或者您可以删除以下行:
$result[0][] = "Select Style";
并将以下内容直接放在for循环之后:
array_unshift($result, "Select Style");
@Denoteone, Following应该可以,
$result[0][] = "Select Style";
for ($x=0;$x<$count;++$x)
{
$result[][] = $content[$x]['name'];
}
使用
函数
可以解决这个问题
<?php
$queue = array("orange", "banana");
array_unshift($queue, "apple", "raspberry");
print_r($queue);
?>
在这段代码之后,$queue数组变成
Array
(
[0] => apple
[1] => raspberry
[2] => orange
[3] => banana
)
从http://php.net/manual/en/function.array-unshift.php 修改
$result=array();
$result=array( 'Select Style' );
顺便说一句,你的代码可以稍微修改一下
$query = "SELECT DISTINCT name FROM ImageInfo";
$db = new connection();
$result = $db->query($query);
$content = array('Select Style');
while($row = mysql_fetch_array($result)){
$content[] = $row['name'];
}
echo json_encode($content);