I've been bashing my head against the wall for a couple of days on this, because all indications are that this SHOULD work, so I'm obviously missing something simple.
First I am using a function to grab an array of user submitted comments
function get_id_comment_info($id) {
global $connection;
$pdo = new PDO('mysql:host='.DB_SERVER.'; dbname='.DB_NAME, DB_USER, DB_PASS);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES "utf8"');
$sql = "SELECT parks.parkid, parks.state, pcomment.parkid, pcomment.comment, pcomment.logname
FROM parks
LEFT JOIN pcomment
ON parks.parkid=pcomment.parkid
WHERE parks.id = '$id'";
$result = $pdo->query($sql);
$cominfo = $result->fetchAll();
return $cominfo;
}
Then, inside of a foreach loop which processes each park by id, I am working with the data:
foreach ($display_result as $parkrow) {
$id = $parkrow['parkid'];
$comments = get_id_comment_info($id);
$cleancom = str_replace("'", '', $comments);
print_r($cleancom);
.
.
.
}
The output for $cleancom is:
Array ( [0] => Array ( [parkid] => 462 [0] => 462 [state] => KS [1] =>
KS [2] => 462 [comment] => I have noticed some others here say don't
waste your time, but I think it's ok. Yes, it's smaller than most, but
there is fun to be had if you are an avid rider. [3] => I have noticed
some others here say don't waste your time, but I think it's ok. Yes,
it's smaller than most, but there is fun to be had if you are an avid
rider. [logname] => John32070 [4] => John32070 ) )
It does not remove the '. If I use preg_replace then the output is simply blank. I am missing something simple, but I just can't see it!
I have tested the str_replace() function and got the following results:
$myArray = array("h'i", array("hi'hi", "yo"));
print_r($myArray);
//RESULT: Array ( [0] => h'i [1] => Array ( [0] => hi'hi [1] => yo ) )
After applying the filter:
$filtered = str_replace( "'", "", $myArray);
print_r($filtered );
//RESULT: Array ( [0] => hi [1] => Array ( [0] => hi'hi [1] => yo ) )
What the previous results show is that any string values inside the top array are indeed being converted (h'i converted to hi) while any values that form part of the multidimensional array (any arrays within arrays) are not hi'hi remained the same. This seems to be how the function was created to work.
One solution is:
$cleancom = [];
foreach ($comments as $key => $value)
{
$cleancom[$key] = str_replace( "'", "", $value );
}
The reason the previous code works is because str_replace() is never being applied to a multidimensional array, while in your previous code it was. The previous code will not work however if you have something like an array within an array within another array, so if that ends up being the case in the future, I suggest you try finding a solution with callback functions.
Let me know if this worked for you.
Want to say something else, you should put the ids in an array, then use MySQL in() function, it only need to execute once, while your method will execute many times.
Related
$samples = [[0], [5], [10], [20], [25], [18], [30]];
$labels = ['fail', 'fail', 'pass', 'pass'];
$classifier = new NaiveBayes();
$classifier->train($samples, $labels);
echo $classifier->predict([14]);
The above code is from php machine library named php ml.
The sample and label are hardcoded in the above code. What i want to do is fill the $sample array from database. But the problem i am seeing is i cannot figure it out as you can see its $sample = [[],[],[]] . Is it array with in an array? And how to populate it
I have populated the $label successfully from db.
$samples = [[0], [5], [10], [20], [25], [18], [30]];
This seems like $samples is an array that contains sub-arrays for each of the sample 0, 5, 10 etc.
According to the NaiveBayes for PHP, the sample paramter expects array.
You can use recursive iteration to flatten your array. This will work for you based on your example data.
On another note, I would try to manipulate your query to provide you the results in the proper format.
This solution creates an unnecessary tax on your resources having to iterate across your array, which I am assuming is going to be fairly large, when a proper query will eliminate the need for this altogether.
Try this:
$samples = [[0], [5], [10], [20], [25], [18], [30]];
$labels = ['fail', 'fail', 'pass', 'pass'];
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($samples));
$results = iterator_to_array($iterator, false);
echo '<pre>';
print_r($results);
print_r($labels);
echo '</pre>';
This will output:
Sample:
Array
(
[0] => 0
[1] => 5
[2] => 10
[3] => 20
[4] => 25
[5] => 18
[6] => 30
)
Labels
Array
(
[0] => fail
[1] => fail
[2] => pass
[3] => pass
)
Good luck!
That is how we can accomplish it. Thank you everyone
while($row = mysqli_fetch_assoc($result)){
array_push($samples, array($row['result_midterm']));
}
I have the following array that I converted from a JSON response of the WP REST API:
Array
(
[0] => Array
(
[id] => 6
[convite_id] => Array
(
[0] => 4
)
[nome_do_convidado] => John Doe
[email_do_convidado] => Array
(
[0] => johndoe#gmail.com
)
)
[1] => Array
(
[id] => 5
[convite_id] => Array
(
[0] => 4
)
[nome_do_convidado] => Lorem
[email_do_convidado] => Array
(
[0] => lorem#gmail.com
)
)
)
And I'm trying to loop the [email_do_convidado] value as:
johndoe#gmail.com
lorem#gmail.com
I've tried with foreach() loop and just get the last one, and now I've tried with while() and get one result too, follow my script:
while (list ($key, $val) = each ($myArray) ) echo $val['email_do_convidado'][$key];
And the result is:
johndoe#gmail.com
What I'm doing wrong here?
Try with a foreach instead of a while. You can extract all the emails by merging all arrays into a final output.
$emails = [];
foreach($myArray as $entry){
$emails = array_merge($emails, $entry['email_do_convidado']);
}
var_dump($emails);
I assume you'll want to do something afterwards will all the emails. I'll leave that up to you.
Its not quite clear, what i understand is that u want the first email of each element, if thats the case u could do this
foreach($array as $value){
echo $value[email_do_convidado][0];
}
On the other hand if u have several emails inside "email_do_convidado" u could loop that other array
foreach($array as $value){
foreach($value[email_do_convidado] as $email){
echo $email;
}
}
Or if u dont want to use a foreach inside a foreach u can
//inside the first foreach.
$emails = implode(',', $value[email_do_convidado]);
//and the u echo $emails
echo $emails;
Hope my answer helps u.
The values you are seeking are in:
$myArray[0]['email_do_convidado'][0]
$myArray[1]['email_do_convidado'][0]
Your code is:
while (list ($key, $val) = each ($myArray) ) {
echo $val['email_do_convidado'][$key];
}
(slightly amended to better style)
So your code is trying to retrieve
$myArray[0]['email_do_convidado'][0]
$myArray[1]['email_do_convidado'][1]
The latter doesn't exist. So I'm afraid you have failed on multiple levels:
your code doesn't do what you intend
your error reporting is not working (PHP is throwing a warning about this you are not seeing)
you haven't attempted to instrument your code to see what's happening (simply putting "email=" before the value in your echo statement would have revealed this).
Try:
echo $val['email_do_convidado'][0];
I have a site which I used JSON to save some data.
Here is how it saves data
{"1":{"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"}}}
Note: I know this is a poor way of doing it but I did it when I was not so vast!
The 1 is the user_id which changes according to the id of the user that takes an exam on the platform. The english, physics are the subjects this user took.
The maximum number of exam a user can take at a time is for so the json string will look like {"1":{"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"},"maths":{"grade":"7","time":"79"},"chemistry":{"grade":"3","time":"48"}}}
First I think this is the best way to save the result as a JSON string
[{"subject":"english","grade":"7","time":"79"}, {"subject":"physics", "grade":"3","time":"48"}}]
My problem is that I want to use PHP to work on the former on. I have done some few stripping of the string and I'm left with this {"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"}}
I tried this chunk
$JSONResult = json_decode($aScore->result);
foreach ($JSONResult as $subjectKey => $aSubject)
{
foreach ($aSubject as $theResult)
{
$userResult = '
Subject: **This is what I've not been able to get**
Grade: '.$theResult->grade.'
Time: '.$theResult->time.'
';
}
}
I tried $aSubject->subjectKey to get the associative key value from the first foreach statement but it did not work
Any help?
Added: Please leave comments about the way the JSON string was stored. I'd love to learn.
You don't need the inner loop. Each subject is just a single object, not an array. And the subject key is just $subjectKey, it's not a part of the object.
$JSONResult = json_decode($aScore->result, true); // to get an associative array rather than objects
foreach ($JSONResult as $subjectKey => $aSubject) {
$userResult = "
Subject: $subjectKey
Grade: {$aSubject['grade']}
Time: {$aSubject['time']}
";
}
DEMO
You could use the second argument to json_decode!
It changes your $JSONResult from stdClass to an associative Array!
Which means you can do something like this:
$str = '{"1":{"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"}}}';
$result = json_decode($str, true); // Put "true" in here!
echo "<pre>".print_r($result, true)."</pre>"; // Just for debugging!
Which would output this:
Array
(
[1] => Array
(
[english] => Array
(
[grade] => 7
[time] => 79
)
[physics] => Array
(
[grade] => 3
[time] => 48
)
)
)
And in order to loop through it:
foreach ($result as $idx => $exams) {
echo $exams['english']['grade']."<br>";
echo $exams['physics']['grade']."<br>";
}
Which would output this:
7
3
Update
Without knowing the containing arrays data (Based on the example above)
$exams will be an Array (which could contain any sort of information):
Array
(
[english] => Array
(
[grade] => 7
[time] => 79
)
[physics] => Array
(
[grade] => 3
[time] => 48
)
)
If you want to loop through $exams:
foreach ($result as $idx => $exams) {
foreach ($exams as $subject => $info) {
echo $info['grade']."<br>";
}
}
This would produce the same output as the above example, without needing to know a subject name!
I've searched around and I found some similar questions asked, but none that really help me (as my PHP abilities aren't quite enough to figure it out). I'm thinking that my question will be simple enough to answer, as the similar questions I found were solved with one or two lines of code. So, here goes!
I have a bit of code that searches the contents of a given directory, and provides the files in an array. This specific directory only has .JPG image files named like this:
Shot01.jpg
Shot01_tn.jpg
so on and so forth. My array gives me the file names in a way where I can use the results directly in an tag to be displayed on a site I'm building. However, I'm having a little trouble as I want to limit my array to not return items if they contain "_tn", so I can use the thumbnail that links to the full size image. I had thought about just not having thumbnails and resizing the images to make the PHP easier for me to do, but that feels like giving up to me. So, does anyone know how I can do this? Here's the code that I have currently:
$path = 'featured/';
$newest = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS));
$array = iterator_to_array($newest);
foreach($array as $fileObject):
$filelist = str_replace("_tn", "", $fileObject->getPathname());
echo $filelist . "<br>";
endforeach;
I attempted to use a str_replace(), but I now realize that I was completely wrong. This returns my array like this:
Array
(
[0] => featured/Shot01.jpg
[1] => featured/Shot01.jpg
[2] => featured/Shot02.jpg
[3] => featured/Shot02.jpg
[4] => featured/Shot03.jpg
[5] => featured/Shot03.jpg
)
I only have 3 images (with thumbnails) currently, but I will have more, so I'm also going to want to limit the results from the array to be a random 3 results. But, if that's too much to ask, I can figure that part out on my own I believe.
So there's no confusion, I want to completely remove the items from the array if they contain "_tn", so my array would look something like this:
Array
(
[0] => featured/Shot01.jpg
[2] => featured/Shot02.jpg
[4] => featured/Shot03.jpg
)
Thanks to anyone who can help!
<?php
function filtertn($var)
{
return(!strpos($var,'_tn'));
}
$array = Array(
[0] => featured/Shot01.jpg
[1] => featured/Shot01_tn.jpg
[2] => featured/Shot02.jpg
[3] => featured/Shot02_tn.jpg
[4] => featured/Shot03.jpg
[5] => featured/Shot03_tn.jpg
);
$filesarray=array_filter($array, "filtertn");
print_r($filesarray);
?>
Just use stripos() function to check if filename contains _tn string. If not, add to array.
Use this
<?php
$array = Array(
[0] => featured/Shot01.jpg
[1] => featured/Shot01_tn.jpg
[2] => featured/Shot02.jpg
[3] => featured/Shot02_tn.jpg
[4] => featured/Shot03.jpg
[5] => featured/Shot03_tn.jpg
)
foreach($array as $k=>$filename):
if(strpos($filename,"_tn")){
unset($array[$k]);
}
endforeach;
Prnt_r($array);
//OutPut will be you new array removed all name related _tn files
$array = Array(
[0] => featured/Shot01.jpg
[2] => featured/Shot02.jpg
[4] => featured/Shot03.jpg
)
?>
I can't understand what is the problem? Is it required to add "_tn" to array? Just check "_tn" existence and don't add this element to result array.
Try strpos() to know if filename contains string "_tn" or not.. if not then add filename to array
$path = 'featured/';
$newest = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS));
$array = iterator_to_array($newest);
$filesarray = array();
foreach($array as $fileObject):
// Check - string contains "_tn" substring or not
if(!strpos($fileObject->getPathname(), "_tn")){
// Check - value already exists in array or not
if(!in_array($fileObject->getPathname(), $filesarray)){
$filesarray[] = $fileObject->getPathname();
}
}
endforeach;
print_r($filesarray);
I'm very new to php and I've been spending quite some type understanding how to pass arguments from Python to php and conversely.
I now know how to pass single variables, but I am still stuck and can't seem to find an answer to this one:
Php calls a Python script (that part works) that returns a list of strings. I'd like to process this list in php.
When I try:
print mylist
in myscript.py, and then :
$result = exec('python myscript.py')
it looks like php understands $result as a single string (which I agree makes sense).
I understand that maybe json can help or that I somehow need to use a dictionary instead of a list in python. However I can't figure out how exactly.
If anyone can help, it will be much appreciated! Thanks!
For instance:
myscript.py
import json
D = {'foo':1, 'baz': 2}
print json.dumps(D)
myscript.php
<?php
$result = json_decode(exec('python myscript.py'), true);
echo $result['foo'];
You're using stdin / stdout to transfer the data between the programs, that means you'll have to encode your structure somehow in order to let your receiving program parse the elements.
The simplest thing would be to have python output something like a comma separated list
Adam,Barry,Cain
and use
$result = explode(exec('python myscript.py'));
on the php side to turn your string data back into an array.
If the data is unpredictable (might contain commas) or more structured (more than just a simple list) then you should go for something like json as suggested by Krab.
Apparently your question was misleading. Was redirected here thinking this a solution for converting python lists to php array.
Posting a naive solution for ones wanting to convert lists to php array.
// Sample python list
$data = '[["1","2","3","4"],["11","12","13","14"],["21","22","23","24"]]';
// Removing the outer list brackets
$data = substr($data,1,-1);
$myArr = array();
// Will get a 3 dimensional array, one dimension for each list
$myArr =explode('],', $data);
// Removing last list bracket for the last dimension
if(count($myArr)>1)
$myArr[count($myArr)-1] = substr($myArr[count($myArr)-1],0,-1);
// Removing first last bracket for each dimenion and breaking it down further
foreach ($myArr as $key => $value) {
$value = substr($value,1);
$myArr[$key] = array();
$myArr[$key] = explode(',',$value);
}
//Output
Array
(
[0] => Array
(
[0] => "1"
[1] => "2"
[2] => "3"
[3] => "4"
)
[1] => Array
(
[0] => "11"
[1] => "12"
[2] => "13"
[3] => "14"
)
[2] => Array
(
[0] => "21"
[1] => "22"
[2] => "23"
[3] => "24"
)
)
$str = "[u'element1', u'element2', 'element3']";
$str = str_replace( array("u'", "[", "]"), array("'", ""), $str );
$strToPHPArray = str_getcsv($str, ",", "'");
print_r( $strToPHPArray );
Outputs
Array
(
[0] => element1
[1] => element2
[2] => element3
)