add staitc value to starting of an array which is formed by fetching results from MySQL
How do I add a static value as first element or starting of my array? The data for array is coming from my database.
Below I am trying to add "Select Style" in the front but not it is just combing my first t开发者_如何学Co elements.
$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);
Your issue seems to be with the following lines
$result[0][] = "Select Style";
and
$result[$x][] = $content[$x]['name'];
You are setting the first value in the array as "Select Style" then in the first iteration of the for loop you have $x == 0 so it is overriding the value you put in
You can change
    $result[$x][] = $content[$x]['name']; 
to
    $result[][] = $content[$x]['name']; 
Alternatively you can remove the following line:
    $result[0][] = "Select Style";  
And place the following directly after your for loop:
    array_unshift($result, "Select Style"); 
@Denoteone, Following should do the trick,
$result[0][] = "Select Style";
for ($x=0;$x<$count;++$x)
{
    $result[][] = $content[$x]['name'];
}
Using
array_unshift
can solve the problem
<?php
  $queue = array("orange", "banana");
  array_unshift($queue, "apple", "raspberry");
  print_r($queue);
?>
after this code, the $queue array becomes
Array
(
  [0] => apple
  [1] => raspberry
  [2] => orange
  [3] => banana
)
from http://php.net/manual/en/function.array-unshift.php
Change this
$result=array();
to this
$result=array( 'Select Style' );
And, btw, your code could use a little revamp
$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);
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论