PHP Array question? - php

Hope you are fine. My question :
In MYSQL i have a table with this type of field
Field Name: TAGS
Value : xavier,celine,marise,leon,john,cathy,polux,maurice
In PHP i do this
$xwords = array();
function array_rpush(&$arr, $item)
{
$arr = array_pad($arr, -(count($arr) + 1), $item);
}
$tags = requete("SELECT tags FROM tbl_tags LIMIT 1;");
while($dtags = mysql_fetch_assoc($tags)){
$words .= array_rpush($xwords, $dtags['tags']);
}
// MY ARRAY XWORDS FOR DEBUG
//
// Array ( [0] => xavier, celine, marise, leon, john, cathy, polux, maurice
//
My script need to find the first letter of each word in this list and check if he match with A / B / C (i create an A-Z index page)
// COUNT $XWORDS VALUE
$total = count($xwords);
// total =1
for($i=0; $i < $total; $i++)
{
$wtags = explode(",",$xwords[$i]);
// wtags = Array ( [0] => xavier [1] => celine [2] => marise... )
while (list($idx,$val) = each($wtags)) {
echo $val{0}."<br>";
echo substr($val,0,1)."<br>";
}
}
echo $val{0}."<br>"; OR echo substr($val,0,1)."<br>" give me just x and nothing after (while give me only the first letter for the first record in array... amazing :))
Perhaps you can help me find a solution. Thanks

The problem with your code is that it generates:
Array ( [0] => "xavier" [1] => " celine" [2] => " marise"... )
So $val[0] = " ". Try to trim($val):
$val = trim($val);
print $val[0];

$sum = array();
foreach($wtags as $tag){
$tag = trim($tag);
empty($sum[$tag{0}]) ? // if we don't have a $sum element for this letter
$sum[$tag{0}] = 1 : // we initialize it
$sum[$tag{0}]++; // else, we sum 1 element to the count.
//$tag{0} is the first letter.
}
// the array $sum has the total of tags under each letter
//
// $sum[x] = 1
// $sum[c] = 2
// $sum[m] = 2
// $sum[l] = 1
// $sum[j] = 1
// $sum[p] = 1

Related

Multiple Array values (some value same) how to get only 2 values same

Multiple values ​​in a single array (some value similar)
how to get
One of them is to get the array that is similar values
minimum 1 and maximum 2 times repeat
for Example This array -
$array_value = array('ab','ab','cd','de','ab','cd','ab','de','xy');
foreach($array_value as $value){
}
I want output - ab, ab,cd, cd, de, xy
array_count_values return the repetition of specific value in array. So, you can use it to simplify the code and quickly implement it.
$array_value = array('ab','ab','cd','de','ab','cd','ab','de','xy');
// Get count of every value in array
$array_count_values = array_count_values($array_value);
$result_array = array();
foreach ($array_count_values as $key => $value) {
// Get $value as number of repetition of value and $key as value
if($value > 2) {
$value = 2;
array_push($result_array, $key);
array_push($result_array, $key);
} else {
for ($i=0; $i < $value; $i++) {
array_push($result_array, $key);
}
}
}
print_r($result_array);
I think your output shuold have two de not one?
Anyway here is the code with explanations in comments:
<?php
$array_value = array('ab','ab','cd','de','ab','cd','ab','de','xy');
$arr_count = []; //we use this array to keep track of how many times we've added this
$new_arr = []; //we add elements to this array, or not.
foreach($array_value as $value){
// we've added it before
if (isset($arr_count[$value])) {
// we only add it again one more time, no more.
if ($arr_count[$value] < 2) {
$arr_count[$value]++;
$new_arr[] = $value;
}
}
// we haven't added this before
else {
$arr_count[$value] = 1;
$new_arr[] = $value;
}
}
sort($new_arr);
print_r($new_arr);
/*
(
[0] => ab
[1] => ab
[2] => cd
[3] => cd
[4] => de
[5] => de
[6] => xy
) */
PHP Demo

Reading data from a text file using Strpos & Substr to remove commas between and a while loop to repeat for each row

I'll try and be as clear as I can with what my problem is here, I've been working on this one for a while now and can't seem to get my head around it. Basically, I'm trying to:
Read numbers from a text file & store them in a 2D array
Remove any commas in the text file and store the remaining data in a table format
Using strpos & substr to extract the data, leaving behind unwanted commas
Then using a while loop to repeat this process so every line in the text file is read one at a time until all the lines are read.
At first my code was stating what lines I had errors in and I have since amended but now the php page doesnt seem to load at all. Is there some sort of error within my while loop statement?
Here is the php code I'm currently working with that doesnt seem to be loading:
$fileopen = fopen($file,'r') or die("Sorry, cannot find the file $file");
if($fileopen){
while (($buffer=fgets($fileopen,4096))!==false){
}
if(!feof($fileopen)){
echo "Error:unexpected fgets() fail\n";
}
fclose($fileopen);
}
$filearray = array();
$rows = 0;
$columns = 0;
$fileopen = fopen($file,'r') or die("Sorry, cannot open $file");
while(!feof($fileopen))
{
$line = fgets($fileopen);
$length = strlen($line);
$pos = 0;
$comma = 0;
while($pos < length) {
$comma = strpos($line,",",$comma);
$filearray[$rows][$columns] = substr($line,$pos,$comma);
$pos = $comma +1;
$columns++;
}
$columns = 0;
$rows++;
}
This section is essentially displaying the extracted data from the text file in a table format:
function array_transpose($filearray)
{
array_unshift($filearray, NULL);
return call_user_func_array('array_map', $filearray);
}
echo"<h1></h1>";
echo "<table border = 0 >";
for($row=0; $row<$count; $row++){
print "<tr>";
for($col=0; $col<$count; $col++){
echo "<td>".$array[$row][$col]."</td>";
}
}
echo "</table>";
It was quite the challenge for me to get this one to work, but I managed to do it. I've put comments inside the code to explain what's happening. The reasons it didn't work for you (as I said in the comments) was because you were creating an infinite loop. The $pos integer was always smaller than your $length integer. So the while() loop would never break.
Another issue that you didn't encounter yet was the use of $comma as the length for substr(). Because strpos() returns you the actual position and not the position relative to the offset, this would cause problems. That's why you needed to save the previous position of the delimiter (comma) and substract that from the current position of the delimiter.
Anyway, here is my example code. It's giving you the result that you need. It's up to you to incorporate it into your own code.
<?php
// Initial variables
$result = array();
$key = 0;
// Open the file
$handle = fopen("numbers.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
// First we set the delimiter into a variable
$delimiter = ',';
// Some integers we're going to use for our loop
$pos = 0; // The current position
$comma = 0; // Position of the next comma
$innerkey = 0; // Key used for the 2D result array
$previous = 0; // Previous comma position
$loops = 0; // Number of loops
$nr_commas = substr_count($line, $delimiter); // Number of commas in a single line
while($loops <= $nr_commas) {
// Get the position of the next comma
$comma = strpos($line,$delimiter,$comma);
// Make sure a comma is found
if($comma !== false){
// Put the substring into the result array using $pos as the offset
// and calculating the length by substracting the position of the previous
// comma from the current comma.
$result[$key][$innerkey] = substr($line,$pos,$comma - $previous);
// Add 1 to the previous comma or it will include the current comma in the result
$previous = $comma + 1;
$pos = $comma + 1;
$innerkey++;
$loops++;
$comma++;
} else {
// In case no more commas are found, we still need to add the last integer
$loops++;
$result[$key][$innerkey] = substr($line,strrpos($line,$delimiter)+1);
}
}
$key++;
}
fclose($handle);
} else {
echo "Unable to open the file";
}
echo "<pre>";
print_r($result);
echo "</pre>";
?>
TXT File used:
3,34,2,35,4,234,34,2,53,4
5,4,23,6,67,324,5,34,5
345,67,3,45,6,7
Result:
Array
(
[0] => Array
(
[0] => 3
[1] => 34
[2] => 2
[3] => 35
[4] => 4
[5] => 234
[6] => 34
[7] => 2
[8] => 53
[9] => 4
)
[1] => Array
(
[0] => 5
[1] => 4
[2] => 23
[3] => 6
[4] => 67
[5] => 324
[6] => 5
[7] => 34
[8] => 5
)
[2] => Array
(
[0] => 345
[1] => 67
[2] => 3
[3] => 45
[4] => 6
[5] => 7
)
)

Codeigniter : how to multiply matrices array data from db?

well i have a problem with logic of matrices multiplication in php; the data comes from the database in the form of an one dimension array (Array ( [0] => 1.0000 [1] => 0.5000 [2] => 3.0000 [3] => 2.0000 [4] => 1.0000 [5] => 5.0000 [6] => 0.3333 [7] => 0.2000 [8] => 1.0000 ) ), that I need to transform into a matrice. The dimension of the original array is a square number (in this case 9), so the result matrice will have two equal dimensions, both equal to the square root (3) of the original data array.
The result matrice has to be multiplied by itself, using the pattern in the image below:
I have made some research before, but none of them were right.
i have the following code i used in the model to create the algorithm:
function hitung_matriks(){
$query = $this->db->query("select * from banding b
inner join kriteria a on a.Kd_Kriteria1 = b.Kd_Kriteria1");
$dt_matriks = $query->result();
$data = array();
foreach($dt_matriks as $a){
$data[] = $a->Nilai_Banding;
}
echo "<pre>";
print_r($data);
echo "</pre>";
$c = array();
for($i=1;$i<=sqrt(count($data));$i++){
$d = array();
$isi=0;
for($j=1;$j<=sqrt(count($data));$j++){
$isi = $data[$i][$j] * $data[$j][$i];
$d[] = $isi;
}
$c[] = $d;
}
echo "<pre>";
print_r($c);
echo "</pre>";die();
}
and the result of each array comes 0.
I want to make this code works to be like this :
please help me :'(
Updated answer:
Way to transform $data array into a matrice:
$data = array(1.0000, 0.5000, 3.0000, 2.0000, 1.0000, 5.0000, 0.3333, 0.2000, 1.0000);
$data2 = array();
$j = 0;
$k = 0;
for($i=0;$i<count($data);$i++){
if($j < sqrt(count($data)) ){
$data2[$j][$k] = $data[$i];
$j++;
}else{$j = 0; $k++;}
}
About matrix multiplication, I found this interesting post: http://sickel.net/blogg/?p=907
Using the exact function found there:
function matrixmult($m1,$m2){
$r=count($m1);
$c=count($m2[0]);
$p=count($m2);
if(count($m1[0])!=$p){throw new Exception('Incompatible matrixes');}
$m3=array();
for ($i=0;$i< $r;$i++){
for($j=0;$j<$c;$j++){
$m3[$i][$j]=0;
for($k=0;$k<$p;$k++){
$m3[$i][$j]+=$m1[$i][$k]*$m2[$k][$j];
}
}
}
return($m3);
}
$c = matrixmult($data2, $data2);
foreach($c as $k => $v){
$i = 0;
foreach($v as $kk => $vv){
echo $vv . ' | ';
$i++;
if($i == count($v))
echo '<br/>';
}
}
The result is quite close to the needed pattern:
2.9999 | 1.6 | 8.5 |
5.6665 | 3 | 16 |
1.0666 | 0.56665 | 2.9999 |
The slight difference comes from the rounding method. If that's an issue, see round() function.
sqrt() function is for calculating square root. If you want to loop all elements in array then remove sqrt() call.
In PHP, array usually zero-based index, so you need to replace $i=1, $j=1 to start from 0 in your for loop.
See Matrix multiplication

Need Help in building a logic

I need to get all the positions of a character in a string in a form of an array. I know about the php function strpos() but it does not accept an array as an argument.
This is required:
$name = "australia"; //string that needs to be searched
$positions_to_find_for = "a"; // Find all positions of character "a" in an array
$positions_array = [0,5,8]; // This should be the output that says character "a" comes at positions 0, 5 and 8 in string "australia"
Question: What Loops can help me build a function that can help me achieve the required output?
You can use a for to loop that string:
$name = "australia";
$container = array();
$search = 'a';
for($i=0; $i<strlen($name); $i++){
if($name[$i] == $search) $container[] = $i;
}
print_r($container);
/*
Array
(
[0] => 0
[1] => 5
[2] => 8
)
*/
Codepad Example
No loops necessary
$str = 'australia';
$letter='a';
$letterPositions = array_keys(
array_intersect(
str_split($str),
array($letter)
)
);
var_dump($letterPositions);

Array not populating correctly

I am using the following code to populate an array:
$number = count ($quantitys);
$count = "0";
while ($count < $number) {
$ref[$count] = postcodeUnknown ($prefix, $postcodes[$count]);
$count = $count +1;
}
postcodeUnknown returns the first row from a mysql query, using a table prefix and an element from an array named postcodes. $postcodes contains strings that should return a different row each time though the loop.
Which I'd expect to create an array similar to:
Array ([0] =>
Array ([0] => some data [1] => more data)
[1] =>
Array ([0] => second row [1] => even more...)
)
But it's not. Instead it's creating a strange array containing the first results over and over until the condition is met, eg:
simplified result of print_r($ref);
Array (
[0] => Array ([0] => some data [1] => more data)
)
Array(
[0] => Array (
[0] => the first arrays content...
[1] => ...repeated over again until the loop ends
)
)
And I'm at a loss to understand why. Anyone know better than me.
Try
$number = count ($quantitys);
$count = "0";
while ($count < $number) {
$ref1[$count] = postcodeUnknown ($prefix, $postcodes[$count]);
$ref2[] = postcodeUnknown ($prefix, $postcodes[$count]);
$ref3[$count][] = postcodeUnknown ($prefix, $postcodes[$count]);
$count = $count +1;
}
echo "<pre>";
print_r($ref1);
print_r($ref2);
print_r($ref3);
echo "</pre>";
Try that to see if any of those get an output you are looking for.
Uh, add a print to postcodeUnknown and check if its actually passing different postcodes or the same thing all the time?
ie
function postcodeUnkown($a,$b){
echo var_dump($a).var_dump($b);
//the rest
}
Also, why two different variables? ($quantitys and $postcodes).
Also, you might want to replace the while loop with for:
for($i=0;$i<$number;$i++){
$ref[$i] = postcodeUnknown ($prefix, $postcodes[$i]);
}
your variable count should not be a string, try this
$number = count ($quantitys);
$count = 0;
while ($count < $number) {
$ref[$count] = postcodeUnknown ($prefix, $postcodes[$count]);
$count = $count +1;
}

Categories