Hallo allemaal,
ik ben een complete noob op gebied van php, dus ik zal wel ergens in mijn script een domme fout hebben staan. Ik maak een array en vul die met gegevens uit een database, en daarna wil ik die gegevens weergeven.
Nou werkt het niet, helaas. Maar de array wordt wel goed gevult, dit heb ik gecheckt met: echo "<pre>" . print_r($items, true) . "</pre>";
Dus de fout zal dan moeten zitten in de foreach, ik hoop dat iemand me hiermee kan helpen want ik zit er al een tijdje behoorlijk vast op.
Het gaat fout bij de onderste foreach. Lijntje 73
Code:
<?php
$text = 'ni';//strtolower($_GET["term"]);
if (!$text) return;
$sql = "SELECT artistID, artistname FROM artists WHERE artistname LIKE '%".mysql_real_escape_string($text)."%' LIMIT 5";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result))
{
$items[] = array($row['artistname'] => $row['artistID']);
}
function array_to_json( $array ){
if( !is_array( $array ) ){
return false;
}
$associative = count( array_diff( array_keys($array), array_keys( array_keys( $array )) ));
if( $associative ){
$construct = array();
foreach( $array as $key => $value ){
// We first copy each key/value pair into a staging array,
// formatting each key and value properly as we go.
// Format the key:
if( is_numeric($key) ){
$key = "key_$key";
}
$key = "\"".addslashes($key)."\"";
// Format the value:
if( is_array( $value )){
$value = array_to_json( $value );
} else if( !is_numeric( $value ) || is_string( $value ) ){
$value = "\"".addslashes($value)."\"";
}
// Add to staging array:
$construct[] = "$key: $value";
}
// Then we collapse the staging array into the JSON form:
$result = "{ " . implode( ", ", $construct ) . " }";
} else { // If the array is a vector (not associative):
$construct = array();
foreach( $array as $value ){
// Format the value:
if( is_array( $value )){
$value = array_to_json( $value );
} else if( !is_numeric( $value ) || is_string( $value ) ){
$value = "'".addslashes($value)."'";
}
// Add to staging array:
$construct[] = $value;
}
// Then we collapse the staging array into the JSON form:
$result = "[ " . implode( ", ", $construct ) . " ]";
}
return $result;
}
$result = array();
echo "<pre>" . print_r($items, true) . "</pre>";
foreach ($items as $key=>$value) {
if (strpos(strtolower($key), $text) !== false) {
array_push($result, array("id"=>$value, "label"=>$key, "value" => strip_tags($key)));
}
if (count($result) > 11)
break;
}
echo array_to_json($result);
mysql_close($link);
?>
2.191 views