$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']));
}
Related
I will try to explain the data I'm working with first, then I'll explain what I hope to do with the data, then I'll explain what I've tried so far. Hopefully someone can point me in the right direction.
What I'm working with:
I have an array containing survey responses. The first two items are the two answers for the first question and responses contains the number of people who selected those answers. The last three items are the three answers for the other question we asked.
Array
(
[0] => Array
(
[survey_id] => 123456789
[question_text] => Have you made any changes in how you use our product this year?
[d_answer_text] => No
[responses] => 92
)
[1] => Array
(
[survey_id] => 123456789
[question_text] => Have you made any changes in how you use our product this year?
[answer_text] => Yes
[responses] => 30
)
[2] => Array
(
[survey_id] => 123456789
[question_text] => How would you describe your interaction with our staff compared to prior years?
[answer_text] => Less Positive
[responses] => 14
)
[3] => Array
(
[survey_id] => 123456789
[question_text] => How would you describe your interaction with our staff compared to prior years?
[answer_text] => More Positive
[responses] => 35
)
[4] => Array
(
[survey_id] => 123456789
[question_text] => How would you describe your interaction with our staff compared to prior years?
[answer_text] => No Change
[responses] => 72
)
)
What I want to achieve:
I want to create an array where the question_text is used as the key (or I might grab the question_id and use it instead), use the answer_text as a key, with the responses as the value. It would look something like this:
Array
(
[Have you made any changes in how you use our product this year?] => Array
(
[No] => 92
[Yes] => 30
)
[How would you describe your interaction with our staff compared to prior years?] => Array
(
[Less Positive] => 14
[More Positive] => 35
[No Change] => 72
)
)
Here's what I've tried:
$response_array = array();
foreach($result_array as $value){
//$responses_array['Our question'] = array('answer 1'=>responses,'answer 2'=>responses);
$responses_array[$value['question_text']] = array($value['answer_text']=>$value['responses']);
}
This does not work because each loop will overwrite the value for $responses_array[$question]. This makes sense to me and I understand why it won't work.
My next thought was to try using array_merge().
$responses_array = array();
foreach($result as $value){
$question_text = $value['question_text'];
$answer_text = $value['answer_text'];
$responses = $value['responses'];
$responses_array[$question_text] = array_merge(array($responses_array[$question_text],$answer_text=>$responses));
}
I guess my logic was wrong because it looks like the array is nesting too much.
Array
(
[Have you made any changes in how you use our product this year?] => Array
(
[0] => Array
(
[0] =>
[No] => 92
)
[Yes] => 30
)
My problem with array_merge is that I don't have access to all answers for the question in each iteration of the foreach loop.
I want to design this in a way that allows it to scale up if we introduce more questions with different numbers of answers. How can this be solved?
Sounds like a reduce job
$response_array = array_reduce($result_array, function($carry, $item) {
$carry[$item['question_text']][$item['answer_text']] = $item['responses'];
return $carry;
}, []);
Demo ~ https://eval.in/687264
Update
Remove condition (see #Phil comment)
I think you are looking for something like that :
$output = [];
for($i = 0; $i < count($array); $i++) {
$output[$array[$i]['question_text']] [$array[$i]['answer_text']]= $array[$i]['responses'];
}
print_r($output);
Slightly different approach than the answer posted, more in tune with what you'v already tried. Try This:
$responses_array = array();
$sub_array = array();
$index = $result[0]['question_text'];
foreach($result as $value){
$question_text = $value['question_text'];
$answer_text = $value['answer_text'];
$responses = $value['responses'];
if (strcmp($index, $question_text) == 0) {
$sub_array[$answer_text] = $responses;
} else {
$index = $question_text;
$responses_array[$index] = $sub_array;
$sub_array = array();
}
}
Edit: Found my mistake, updated my answer slightly, hopefully this will work.
Edit 2: Working with example here: https://eval.in/687275
I am taking information from a JSON feed, and creating a JSON feed that I can use more easily across more devices. The problem I am having is when creating the new array in PHP for the JSON feed, I need to use a foreach loop. Here is my code for the foreach loop:
$obj = json_decode($json);
$json_decode = objectToArray($obj);
$special_number = '0';
$special_number2 = '0';
foreach($json_decode AS $r) {
$info = explode('.', $json_decode[$special_number]['Id']);
$newarray = array( $special_number => array( 'client' => $info['4'], 'placementID' => $info['2'], 'creativeID' => $info['3'], 'dimensions' => $info['3'], 'impressions' => $json_decode[$special_number]['Impressions'], 'bxd' => $json_decode[$special_number]['BXD'], 'viewable_impressions' => $json_decode[$special_number]['ViewableImpressions'], 'exposure' => $json_decode[$special_number]['Exposure'], 'viewability_rate' => $json_decode[$special_number]['ViewableRate'], 'clicks' => $json_decode[$special_number]['AdClicks'], 'mouse_overs' => $json_decode[$special_number]['AdMouseOvers'] ));
$fullarray = array_merge($newarray);
$special_number++;
}
I am basically taking their arrays, reordering the info and getting only the data I need, and creating a new array with it, called $fullarray. Each of the sub arrays I am making are generated each time, is it due to me running a foreach it is destorying the old $fullarray, and creating a new one? It is giving me the following:
Array
(
[0] => Array
(
[client] =>
[placementID] => 3
[creativeID] => 4
[dimensions] => 4
[impressions] => 1
[bxd] => 0
[viewable_impressions] => 0
[exposure] => 0
[viewability_rate] => 0
[clicks] => 1
[mouse_overs] => 1
)
)
I have searched for this, but I can not find it, other threads are about combining different keys and values, I am having to create subarrays to keep the keys the same, and have different values (this is what I want, yes.)
Any help will be appreciated! :)
This should do it:
$fullarray = array()
foreach(...)
{
...
$fullarray = array_merge($fullarray,$newarray);
}
The merge function can take more arrays parameters to be merged, in your case you did not merged the contents of fullarray to the new array, instead you overwrite it.
You may also need to declare full array before foreach
I have an array as so:
$diff_date_results =
Array (
[0] => Array ( [differential] => 7.7 [date] => 2012-12-30 )
[1] => Array ( [differential] => 8.2 [date] => 2012-12-31 )
[2] => Array ( [differential] => 9.9 [date] => 2013-01-03 )
)
I would like to extract all values from the differential key of each of the inner arrays to use the array_sum function on the newly created array.
I have this, which draws out the three numbers for me, but I get php errors for each number as an undefined index. (Notice: Undefined index: 7.7 in C:\wamp\www\jquery\test.php on line 55)
My code thus far is as follows:
$diff_results = array();
foreach($diff_date_results as $entry){
$diff_results[$entry['differential']];
}
print_r($diff_results);
I am sure it is simple, I have been screwing around with it for way too long now, any help would be wonderful!
Thanks.
$diff_results = array();
foreach($diff_date_results as $entry){
$diff_results[] = $entry['differential'];
}
//just for displaying all differential
print_r($diff_results);
Now, you can use array_sum on $diff_results.
Moreover, if you want to have sum then you can use below method too.
$diff_results = "";
foreach($diff_date_results as $entry){
$diff_results = $diff_results + $entry['differential'];
}
//$diff_results will have sum of all differential
echo $diff_results;
$diff_results = array_map($diff_date_results,
function($entry) { return $entry['differential']; });
Do it like this:
$diff_results = array();
foreach($diff_date_results as $key => $entry){
$diff_results[] .= $entry['differential']];
}
print_r($diff_results);
Thanks.
$diff_date_results = array (
0 => array ( 'differential'=> 7.7, 'date' => 20),
1 => Array ( 'differential' => 8.8, 'date' => 20 ),
2 => Array ( 'differential' => 9.8 ,'date' => 20 ),
);
$value_differential=array();
foreach( $diff_date_results as $key=>$value){
print_r($value);
$value_differential[]=$value['differential'];
}
print_r(array_sum($value_differential));
For anyone stumbling across this question as I have, the best solution in my opinion is a working version of Barmars as below:
$diff_results = array_map(function($entry)
{
return $entry['differential'];
},
$diff_date_results);
it's a more elegant, 1 line solution (which I've expand to 5 lines for readability).
I have a array like this.
Array (
[0] => PHP
[1] => ROR
[2] => Python
[3] => JAVA
)
Array (
[0] => WP
[1] => Drupal
[2] => Joomla
[3] => SpreeCommerce
)
Array (
[0] => N2CMS
[1] => Life Ray
[2] => Magento
[3] => Zen Cart
)
Here i need the the above array extract to this below format, the first array use like as column part and others array are use the columns value.
PHP = WP
ROR = Drupal
Python = Joomla
JAVA = SpreeCommerce
PHP = N2CMS
ROR = Life Ray
Python = Magento
JAVA = Zen Cart
Give a a try to array_combine()
Rough code, assuming all array have same length.
$array1=array("PHP","ROR","Python","Java");
$array2=array("WP","Drupal","Joomla","SpreeCommerce");
$array3=array("N2CMS","Life Ray","Magento","Zen Cart");
for($i=0;$i<count($array1);$i++){
echo $array1[$i]."=".$array2[$i]."<br>";
}
for($i=0;$i<count($array1);$i++){
echo $array1[$i]."=".$array3[$i]."<br>";
}
I would do it in a simple function like this:
function mergerArray($array1, $array2)
{
$retArray = array();
// assumes that both are arrays and of equal length.
for($i=0; $$i<count($array1); $i++)
{
$retArray[$array1[$i]]=$array2[$i];
}
return $retArray;
}
$mergedArray=mergerArray($keyMakingArray, $dataHoldingArray);
print_r($mergedArray);
Make sure to do all your checking of inputs before processing - ie, same number of elements, right data etc etc. I am not going to do that for you, this should be a good start allowing you as much flexibility as you need.
I am trying to build a new array from simpleXmlElement. I am getting the information I want, just not in the right hierarchy.
$xmlNew1 = new SimpleXMLElement($responseNew1);
$test = array();
foreach ($xmlNew1->children() as $newChild){
$classIden[] = (string)$xmlNew1->class['id'];
$item[] = (string)$xmlNew1->code;
$family[] = (string)$xmlNew1->family;
for($i=0, $count = count($classIden); $i < $count; $i++) {
$test[$item[$i]][$family[$i]]= $classIden[$i];
}
}
print_r($test);
this gives me:
Array
(
[9522] => Array
(
[Mens Hats] => 44
)
[9522-NC-NO SIZE] => Array
(
[Mens Hats] => 44
)
[B287CSQU] => Array
(
[Boys] => 1
)
but I want
Array
(
[9522] => Array
(
[family] => Mens Hats
[classId] => 44
)
Any suggestion? Thanks!
This should probably do it (to replace the main loop contents):
$id = (string)$newChild->class['id'];
$code = (string)$newChild->code;
$family = (string)$newChild->family;
$items[$code] = array(
'family' => $family,
'classId' => $id,
);
Edit
Forgot to use $newChild instead of $xmlNew1.
I don't know your hierarchy because I do not know much about the HTML. You've hidden the structure. However, you should probably build the array in the format you look for directly.
Let us try to make that less complicated. Let's say you have a variable that would contain all the children. So you can pull apart the iteration and loading these children. Loading:
$xmlNew1 = new SimpleXMLElement($responseNew1);
$newChildren = $xmlNew1->children();
I can not say you if $xmlNew1->children() is sufficient to get you all the xml elements you are looking for, but let's just assume so.
Next part is about the iteration. As written you should build the $test array while you iterate over the children - as you partly already did:
$test = array();
foreach ($newChildren as $newChild) {
...
}
Missing part now is to create your structure in $test:
Array(
[9522] => Array(
[family] => Mens Hats
[classId] => 44
)
I like the suggestion #Jack gives here to first assign the values you want to extract to variables of their own and then create the entry.
$newItem = array(
'family' => $family,
'classId' => $id,
);
$test[$code] = $newItem;
Naturally you have to place that into the iteration. When the iteration is done, the $test array should have the format you're looking for.
I hope this is helpful.