My code outputs several "Array" - php

I just tried to create a spinner using MySQL and PHP, but after a few a hours it displays "ArrayArrayArray" in front of the expected output.
if($_POST['artikel']){
$artikel = nl2br($_POST['artikel']);
$ar = explode("\n\r",$artikel);
$hasil = "";
foreach($ar as $ars){
$newstring1 = explode(" ", $ars);
foreach($newstring1 as $newstring2){
$newstring3 = explode("\n", $newstring2);
foreach($newstring3 as $newstring4){
$newstring5 = explode(",", $newstring4);
foreach($newstring5 as $value){
$cari = mysql_query("select * from sinonim where kata1='$value'");
$j = mysql_num_rows($cari);
if($j>0){
$ka = mysql_fetch_array($cari);
$hasil = $hasil."<span class='re'>".$ka['kata2']." ";
$hasil = explode(",", $hasil);
foreach($hasil as $vv) {
$hasil = $hasil.$vv."</span> ";
}
}else{
$cari2 = mysql_query("select * from sinonim where kata2='$value'");
$j2 = mysql_num_rows($cari2);
if($j2>0){
$ka2 = mysql_fetch_array($cari2);
$hasil = $hasil."<span class='re'>".stripslashes($ka2['kata1'])."</span> ";
}else{
$hasil = $hasil.$value." ";
}
}
}
}
}
}
echo $hasil;
}
The result looks like this
ArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayhello all......
Why is "Array" printed? How can I avoid that?

Your code is a mess. The problem occurs in this part
$hasil = $hasil."<span class='re'>".$ka['kata2']." "; // line 1
$hasil = explode(",", $hasil); // line 2
foreach($hasil as $vv) { // line 3
$hasil = $hasil.$vv."</span> "; // line 4
} // line 5
In line 2 you use explode to split $hasil into an array, then in line 4 you try to append it to itself, although it's an array now not a string. This causes the "Array" output.
Eventually you want to use another variable here. Also you're adding multiple </span>, which will invalidate your HTML. I guess it should look like this:
$hasil = $hasil."<span class='re'>".$ka['kata2']." ";
$temp = explode(",", $hasil);
foreach($temp as $vv) {
$hasil = $hasil.$vv;
}
$hasil = $hasil."</span> ";
But line 4 still doesn't make sense. You're iterating over text tokens, which are already part of the output. What do you want to append here?
In your edit you stated that changing line 4 to $hasil = $vv."</span> "; solved your problem, but it looks like you're still producing invalid HTML and your code is way too complicated for what you're trying to achieve.

Related

Remove certain String from array php

I want to get rid of that string with help of the str_replace function in PHP but I won't work. Can anybody help me?
$sql = "SELECT data from users";
$result = $mysqli->query($sql);
$widgets = [];
while($row = mysqli_fetch_array($result))
{
$widgets[] = $row;
}
$alignment = explode("//",serialize($widgets));
for($i = 0; $i<count($alignment); $i++){
str_replace("a:3:{i:0,:a:2:{:i:0;s:31;q}")
}
?>
As said in http://php.net/manual/en/function.str-replace.php
php_replace take 3 arguments
$replaced = str_replace(search, replaced_by, initial_string, [&replaced]);
Refer str_replace function for clarity, and change your code like below:
$replacedValue = str_replace("a:3:{i:0,:a:2:{:i:0;s:31;q}","",$alignment[$i]);

array_diff doesn't work (PHP)

I have 2 array in my code, like the shown below:
<?php
$kalimat = "I just want to search something like visual odometry, dude";
$kata = array();
$eliminasi = " \n . ,;:-()?!";
$tokenizing = strtok($kalimat, $eliminasi);
while ($tokenizing !== false) {
$kata[] = $tokenizing;
$tokenizing = strtok($eliminasi);
}
$sumkata = count($kata);
print "<pre>";
print_r($kata);
print "</pre>";
//stop list
$file = fopen("stoplist.txt","r") or die("fail to open file");
$stoplist;
$i = 0;
while($row = fgets($file)){
$data = explode(",", $row);
$stoplist[$i] = $data;
$i++;
}
fclose($file);
$count = count($stoplist);
//Cange 2 dimention array become 1 dimention
for($i=0;$i<$count;$i++){
for($j=0; $j<1; $j++){
$stopword[$i] = $stoplist[$i][$j];
}
}
//Filtering process
$hasilfilter = array_diff($kata,$stopword);
var_dump($hasilfilter);
?>
$stopword contain of some stop word like attached in http://xpo6.com/list-of-english-stop-words/
All I wanna do is: I want to check if save the element that exist in array $kata and it is not exist in array $stopword
So I want to delete all the element that exist in both array $kata and $stopword .
I read some suggestion to use array_diff , but somehow it doesn't work to me. Really need your help :( Thanks.
array_diff is what you need, you are right. Here is a simplified version of what you try to do:
<?php
// Your string $kalimat as an array of words, this already works in your example.
$kata = ['I', 'just', 'want', 'to', '...'];
// I can't test $stopword code, because I don't have your file.
// So let's say it's a array with the word 'just'
$stopword = ['just'];
// array_diff gives you what you want
var_dump(array_diff($kata,$stopword));
// It will display your array minus "just": ['I', 'want', 'to', '...']
You should also double check the value of $stopword, I can't test this part (don't have your file). If it does not work for you, I guess the problem is with this variable ($stopword)
There is a problem in your $stopword array. var_dump it to see the issue.array_diff is working correct.
Try following code I wrote to make your $stopword array right:
<?php
$kalimat = "I just want to search something like visual odometry, dude";
$kata = array();
$eliminasi = " \n . ,;:-()?!";
$tokenizing = strtok($kalimat, $eliminasi);
while ($tokenizing !== false) {
$kata[] = $tokenizing;
$tokenizing = strtok($eliminasi);
}
$sumkata = count($kata);
print "<pre>";
print_r($kata);
print "</pre>";
//stop list
$file = fopen("stoplist.txt","r") or die("fail to open file");
$stoplist;
$i = 0;
while($row = fgets($file)){
$data = explode(",", $row);
$stoplist[$i] = $data;
$i++;
}
fclose($file);
$count = count($stoplist);
//Cange 2 dimention array become 1 dimention
$stopword= call_user_func_array('array_merge', $stoplist);
$new = array();
foreach($stopword as $st){
$new[] = explode(' ', $st);
}
$new2= call_user_func_array('array_merge', $new);
foreach($new2 as &$n){
$n = trim($n);
}
$new3 = array_unique($new2);
unset($stopword,$new,$new2);
$stopword = $new3;
unset($new3);
//Filtering process
$hasilfilter = array_diff($kata,$stopword);
print "<pre>";
var_dump($hasilfilter);
print "</pre>";
?>
I hope it helps

Create a list like array when echoed in php

I would like to echo my results from a database and have them look like an array. They don't necessarily have to be an array but look like one. i.e. When i echo my result,
i would want my final result to look like
[10,200,235,390,290,250,250]
When i try the code below:
$query_rg = mysqli_query($link, "SELECT column FROM `table`");
$row_rg = mysqli_fetch_assoc($query_rg);
echo '[';
while ($row = mysqli_fetch_assoc($query_rg)) {
$list = $row['column'];
$listwithcoma = "$list,";
echo ltrim($listwithcoma,',');
}
echo ']'
The result is :
[10,200,235,390,290,250,250,]
You are doing it wrong. ltrim($listwithcoma,',') has no effect.
ltrim — Strip whitespace (or other characters) from the beginning of a string
You can try a simple way with implode.
$list = array();
while ($row = mysqli_fetch_assoc($query_rg)) {
$list[] = $row['column'];
}
echo '[' . implode(',', $list) . ']';
Just use GROUP_CONCAT in query as
$query_rg = mysqli_query($link, "SELECT GROUP_CONCAT(`column` SEPARATOR ', ') as data
FROM `table`");
$row_rg = mysqli_fetch_assoc($query_rg);
print_r($row_rg['data']);
Try like this
$list = array(); //define a array.
while ($row = mysqli_fetch_assoc($query_rg)) {
$list[] = $row['column']; //store column value in array.
}
$lists = "[".implode(",",$list)."]";
echo $lists; //will echo your results.
You should be using rtrim() function instead, that too outside the loop.
$listwithcoma = '';
echo '[';
while ($row = mysqli_fetch_assoc($query_rg)) {
$list = $row['column'];
$listwithcoma .= "$list,";
// echo ltrim($listwithcoma,','); Remove this
}
echo rtrim($listwithcoma,','); // Add this
echo ']';

`json_encode` not working with explode

I have a string containing numbers separated by comma. ie, 1,2,3,6.... I have removed the comma using explode. Now i want to match the corresponding values in database.
My Code is,
$color = "1,2,3,9,5";
$color_split = explode(",", $color);
foreach($color_split as $item)
{
$select_color = "SELECT * FROM tbl_product_color WHERE color_id = '$item'";
$select_color_q = mysqli_query($c, $select_color) or die(mysqli_error($c));
$length = mysqli_num_rows($select_color_q);
if($length > 0)
{
while($select_color_r = mysqli_fetch_object($select_color_q))
{
$var[] = $select_color_r;
}
$var = json_encode($var);
echo '{"color_list":'.$var.'}';
}
else
{
$arr = array('status'=>"notfound");
echo '{"color_list":['.json_encode($arr).']}';
}
}
Now the output is,
{"color_list":[{"color_id":"1","color_name":"White","color_code":"#f2f2f2"}]}
and one error,
Fatal error: [] operator not supported for strings in C:\wamp\www\jithin\get_color.php on line 18
line 18 contains $var[] = $select_color_r;
My required output is,
{"color_list":[{"color_id":"1","color_name":"White","color_code":"#f2f2f2"},{"color_id":"2","color_name":"Black","color_code":"#000000"},{"color_id":"3","color_name":"Red","color_code":"#F000000"},...]}
You don't need to use foreach and explode over here you can simply update your MySql query and code like as
$color = "1,2,3,9,5";
$select_color = "SELECT * FROM tbl_product_color WHERE color_id IN ($color)";
$select_color_q = mysqli_query($c, $select_color) or die(mysqli_error($c));
$arr['color_list'] = array();
if(mysqli_num_rows($select_color_q) > 0)
{
while($select_color_r = mysqli_fetch_object($select_color_q))
{
$var[] = $select_color_r;
}
}else{
$var = array('status'=>"notfound");
}
$arr['color_list'] = $var;
echo json_encode($arr);
you set $var as string in here :
$var = json_encode($var);
but in the next step of foreach you want to use $var as array.
$var[] = $select_color_r;
just remove the following line :
$var = json_encode($var);
and change this line :
echo '{"color_list":'.$var.'}';
to
echo '{"color_list":'.json_encode($var);.'}';

stip slashes from database return with while loop

Can I loop through DB results and remove Slashes?
(I started getting more slashes everytime I edited the text and put it back into the DB)
$db = new connection();
$query = "SELECT * FROM ITEMS, ALPACA_SALES WHERE ITEMS.uid = '$id' AND ALPACA_SALES.uid = ITEMS.uid";
$results = $db->query($query);
$data = array();
while($info = mysql_fetch_array($results))
{
$data[] = stripslashes($info);
}
But I am getting the following error:
Notice: Array to string conversion in /home/content/myfile.php on line 78
When I add the data to the database I do the following:
if (!empty($_POST['more_text']))
{
$more_text = addslashes($_POST['more_text']);
}
else
{
$error = false;
$error_message = "Please add a description.";
}
And then I use UPDATE for the insert into the DB:
$query2 = "UPDATE ALPACA_SALES SET more_text = '$more_text' WHERE uid = '$id'";
$result = $db->query($query2);
You can't run stripslashes() on an array, which is what $info is from storing mysql_fetch_array($results). You could iterate through $info and strip slashes on each entry, or explicitly strip slashes if you don't need to do all of them.
$i=0;
while($infoarray = mysql_fetch_assoc($results))
{
foreach($infoarray as $field=>$value){
$data[$i][$field] = stripslashes($value);
}
$i++;
}
Edit: You can also create a small function to strip slashes in an array, as outlined in the documentation here: http://us.php.net/manual/en/function.stripslashes.php
function stripslashes_deep($value)
{
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
// Example
$array = array("f\\'oo", "b\\'ar", array("fo\\'o", "b\\'ar"));
$array = stripslashes_deep($array);
Do not do that. stripslashes() is not enough to make a string safe to use in an SQL statement. Your code is vulnerable to SQL injection. Use prepared statements and bound parameters instead.

Categories