I have created a Array and are not able to echo values from it. Below I have copy pasted source code results from my browser. As you can see "]=> starts on new line. How can I solve this
using this function:
function remap_alternating(array $values) {
$remapped = array();
for($i = 0; $i < count($values) - 1; $i += 2) {
$remapped[strip_tags(trim($values[$i], " "))] = strip_tags(trim($values[$i + 1], " "));
}
return $remapped;
}
$mapped = remap_alternating($matches[0]);
$keys = str_replace( ':', '', array_keys($mapped) );
$values = array_values($mapped);
$mapped = array_combine($keys, $values);
Result of var_dump($mapped); (Copy Paste from Browser Source Code)
array(32) {
["Age
"]=>
string(9) "21 Yrs.
"
["Ethnicity
"]=>
string(6) "Black
"
["Location
"]=>
string(36) "Dubai, Dubayy, United Arab Emirates
"
My question is how I can get echo $mapped[Age];to work?
Thank you
You can specify the characters to trim in the second argument of trim(): http://us2.php.net/trim
You look to be specifying only " ", in the trim() function you're using. Leave the second argument blank so it will trim the default characters which includes \n.
Related
This question already has answers here:
Converting a number with comma as decimal point to float
(9 answers)
str_pad with a float in php?
(2 answers)
Remove non-numeric characters (excluding periods and commas) from a string (i.e. remove all characters except numbers, commas, and periods)
(5 answers)
Closed 3 years ago.
This is my code where I read csv file (which I get from the bank), parsing it into array & insert it into database:
$csvFile = file('tecajnica.csv');
$keys = str_getcsv(array_shift($csvFile), ';');
foreach ($csvFile as $csvRecord) {
// combine our $csvRecord with $keys array
$csv[] = array_combine($keys, str_getcsv($csvRecord, ';'));
}
foreach( $csv as $row) {
$db2 = new PDO ("odbc:as400");
$sqlf93p = $db2->prepare("INSERT INTO..... VALUES (".$row['sifra'].",".$row['Kupovni2']." ......)
$sqlf93p->execute();
This is how my array looks like:
[0]=>
array(10) {
["id"]=>
string(2) "67"
["drzava"]=>
string(10) "Australija"
["sifra"]=>
string(7) "036 AUD"
["VrijediZa"]=>
string(1) "1"
["Kupovni1"]=>
string(8) "4,5207"
["Kupovni2"]=>
string(8) "4,589597"
}
[1]=>
array(10) {
["id"]=>
string(0) ""
["drzava"]=>
string(5) "Ceska"
["sifra"]=>
string(7) "203 CZK"
["VrijediZa"]=>
string(1) "1"
["Kupovni1"]=>
string(8) "0,277098"
["Kupovni2"]=>
string(8) "0,2821"
}
* * * * * * * etc * * * * * *
So my questions are:
1) Howto convert ["sifra"]=> "203 CZK" to ["sifra"]=> "203" (I want only numeric value to appear before insert)?
2) Howto convert ["Kupovni2"]=> "0,2821" to ["Kupovni2"]=> "0,282100" (I want 6 decimal places before insert)?
Thanks.
Another option could be to replace all non digits using \D+ with an empty string.
$digitsOnly = preg_replace('/\D+/', '', "203 CZK");
echo $digitsOnly; // 203
For appending the zeroes, you might use str_pad:
$parts = explode(',', '0,2821');
$str = implode(',', [$parts[0], str_pad($parts[1], 6, '0', STR_PAD_RIGHT)]);
echo $str; // 0,282100
Php demo
Your code might look like:
foreach( $csv as $row) {
$db2 = new PDO ("odbc:as400");
$sifra = preg_replace('/\D+/', '', $row['sifra']);
$parts = explode(',', $row['Kupovni2']);
$kupovni2 = implode(',', [$parts[0], str_pad($parts[1], 6, '0', STR_PAD_RIGHT)]);
$sqlf93p = $db2->prepare("INSERT INTO..... VALUES (". $sifra . "," . $kupovni2 ." ......);
$sqlf93p->execute();
To get number from a string you can do it this way
$string = '203 CZK';
echo (int) $string;
OR
$string = '203 CZK';
echo filter_var($string, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
To make string to length 8 you can use str_pad
$string = '0,2821';
echo str_pad($string, 8, "0", STR_PAD_RIGHT);
Result :-
0,282100
My question can be understood with an example given below :
Suppose This is the text file, which contains these lines :
hello this is my word file and this is line number 1
hello this is second line and this is some text
hello this is third line and again some text
jhasg djgha sdgasjhgdjasgh jdkh
sdhgfkjg sdjhgf sjkdghf sdhf
s hdg fjhsgd fjhgsdj gfj ksdgh
I want to get each line into a variable
then get all the words of that line into an array
then compare that array which contains words of that line WITH all the words of next lines
if the number of matches of words is more than 3 that line is deleted
so in the above example the output should be :
hello this is my word file and this is line number 1
jhasg djgha sdgasjhgdjasgh jdkh
sdhgfkjg sdjhgf sjkdghf sdhf
s hdg fjhsgd fjhgsdj gfj ksdgh
Because hello this is line is more than 3 words, so the lines containing those words are deleted. Please note that the first line is not deleted because it is unique....
I tried to code myself and created a mess which created 200mb text file with the unlimited number of first line text. Anyways here is the code, dont execute it else you can end up having your hard disk full.
<?php
$fileA = fopen("names.txt", "r");
$fileB = fopen("anothernames.txt", "r");
$fileC = fopen("uniquenames.txt", "w");
while(!feof($fileA))
{
$line = fgets($fileA);
$words = explode(" ", $line);
$size = count($words);
while(!feof($fileA))
{
$line1 = fgets($fileB);
$words1 = explode(" ", $line1);
$size1 = count($words1);
$c=0;
for($i=0; $i<$size; $i++)
{
for($j=0; $j<$size1; $j++)
{
if($words[$i]==$words1[$j])
$c++;
}
}
if($c<3)
fwrite($fileC, $line);
}
}
fclose($fileA);
fclose($fileB);
fclose($fileC);
?>
Thanks
An easy approach would be the following:
read all the lines, using file()
create an array, containing the sentence, indexed by each word.
finally build a blacklist of every sentence which appears in any of the arrays, counting more than 3 entries for any word.
Then print every line, except the blacklisted:
Example:
<?php
$lines = array("hello this is my word file and this is line number 1",
"hello this is second line and this is some text",
"hello this is third line and again some text",
"jhasg djgha sdgasjhgdjasgh jdkh",
"sdhgfkjg sdjhgf sjkdghf sdhf",
"s hdg fjhsgd fjhgsdj gfj ksdgh");
//$lines = file("path/to/file");
$result = array();
//build "count-per-word" array
foreach ($lines AS $line){
$words = explode(" ", $line);
foreach ($words AS $word){
$word = strtolower($word);
if (isset($result[$word]))
$result[$word][] = $line;
else
$result[$word] = array($line);
}
}
//Blacklist each sentence, containing a word appearing in 3 sentences.
$blacklist = array();
foreach ($result AS $word => $entries){
if (count($entries) >= 3){
foreach($entries AS $entry){
$blacklist[] = $entry;
}
}
}
//list all not blacklisted.
foreach ($lines AS $line){
if (!in_array($line, $blacklist))
echo $line."<br />";
}
?>
Output:
jhasg djgha sdgasjhgdjasgh jdkh
sdhgfkjg sdjhgf sjkdghf sdhf
s hdg fjhsgd fjhgsdj gfj ksdgh
Note, that this will also blacklist a single sentence containing 3 times the same word, such as "Foo Foo Foo bar".
To aovid this, check if the line is already "known" for a certain word before pushing it to the array:
foreach ($words AS $word){
if (isset($result[$word])){
if (!in_array($line, $result[$word])){
$result[$word][] = $line;
}
}else
$result[$word] = array($line);
}
#second
while(!feof($fileA))
#should be
while(!feof($fileB))
and
if($c<3)
fwrite($fileC, $line);
#should
if($c<3){
fwrite($fileC, $line);
continue 2;
}
but
then compare that array which contains words of that line WITH all the words of next lines
makes only sence when you compare the file with itself!
EDIT:my post makes no sence at all, read note from prev post!
Why not just array_intersect?
php > $l1 = 'hello this is my word file and this is line number 1';
php > $l2 = 'hello this is second line and this is some text';
php > $a1 = explode(" ", $l1);
php > $a2 = explode(" ", $l2);
php > var_dump(array_intersect($a1, $a2));
array(7) {
[0]=>
string(5) "hello"
[1]=>
string(4) "this"
[2]=>
string(2) "is"
[6]=>
string(3) "and"
[7]=>
string(4) "this"
[8]=>
string(2) "is"
[9]=>
string(4) "line"
}
if (count of intersection >= 3) {
skip line
}
Or am I reading your "matching" too loosely?
Note: I can't use break or next line functions as i am using FPDF
I am having a problem with php strings. I am having a string where i want to show atmost 12 characters in first row and remaining in second row. So basically i want to break string into two parts and assign to two variables so that i can print those two variables. I have tried following code :-
if($length > 12)
{
$first400 = substr($info['business_name'], 0, 12);
$theRest = substr($info['business_name'], 11);
$this->Cell(140,22,strtoupper($first400));
$this->Ln();
$this->Cell(140,22,strtoupper($theRest));
$this->Ln();
}
But using this I am getting as shown below :
Original String : The Best Hotel Ever
Output :
The Best Hot
Tel Ever
It is breaking a word, i don't want to break the word, just check the length and if within 12 characters all the words are complete then print next word in next line. Like this :
Desired OutPut:
The Best
Hotel Ever
Any suggestions ?
I see no built-in function to do it, however you could explode on spaces, and re-build your string until the length with the next words get over 12, everything else going to the second part :
$string = 'The Best Hotel Ever';
$exp = explode(' ', $string);
if (strlen($exp[0]) < 12) {
$tmp = $exp[0];
$i = 1;
while (strlen($tmp . ' ' . $exp[$i]) < 12) {
$tmp .= " " . $exp[$i];
$i++;
}
$array[0] = $tmp;
while (isset($exp[$i])) {
$array[1] .= ' ' . $exp[$i];
$i++;
}
$array[1] = trim($array[1]);
} else {
$array[0] = '';
$array[1] = trim(implode (' ', $exp));
}
var_dump($array);
// Output : array(2) { [0]=> string(8) "The Best" [1]=> string(10) "Hotel Ever" }
// $string1 = 'The';
// array(2) { [0]=> string(3) "The" [1]=> string(0) "" }
// $string2 = 'Thebesthotelever';
// array(2) { [0]=> string(0) "" [1]=> string(16) "Thebesthotelever" }
Im not too crash hot on PHP but it seems to be a simple case of which element of the string you are accessing is futher across from where you want to be:
Try:
if($length > 12)
{
$first400 = substr($info['business_name'], 0, 8);
$theRest = substr($info['business_name'], 11);
$this->Cell(140,22,strtoupper($first400));
$this->Ln();
$this->Cell(140,22,strtoupper($theRest));
$this->Ln();
}
For further help check out because you need to remember to count from zero up:
http://php.net/manual/en/function.substr.php
I have an array of objects that I am looping through. I need to create an array that contains items in the format LASTNAME, FIRSTNAME.
When I do this I end up with an array of lastname, firstname, lastname, firstname etc. because it interprets my comma in the text as a separator for two array values.
JSON (example):
[
{"lastname":"Levy","firstname":"Robert"},
{"lastname":"Johannenson","firstname":"Svenn"},
{"lastname":"Smith","firstname":"Albertson"}
]
then
$authors = array();
for ($i = 0; $i < count($index); ++$i) {
$at = trim($index[$i]->lastname) . ", " . trim($index[$i]->firstname);
$authors[] = $at;
}
Then $authors contains
["Levy","Robert","Johannenson","Svenn","Smith","Albertson"]
instead of the desired:
["Levy, Robert","Johannenson, Svenn","Smith, Albertson"]
I'm really not new to this but this has me stumped. I could try some kind of character replacement after the array is made (e.g. using | as a separator then doing a str_replace or something) but am looking for a more elegant way.
Here is your example
$index = json_decode('[
{"lastname":"Levy","firstname":"Robert"},
{"lastname":"Johannenson","firstname":"Svenn"},
{"lastname":"Smith","firstname":"Albertson"}
]');
$authors = array();
for ($i = 0; $i < count($index); ++$i){
$at = trim($index[$i]->lastname) . ", " . trim($index[$i]->firstname);
$authors[] = $at;
}
and here is the output of $authors
array(3) {
[0]=>
string(12) "Levy, Robert"
[1]=>
string(18) "Johannenson, Svenn"
[2]=>
string(16) "Smith, Albertson"
}
So everything seems to be correct.
Can you provide full source code?
The result is parsed further on in the script and was causing the output to break. PHP is working as it should. Thanks for all the quick answers.
I have a mapped Array named: $mapped
Below is a result of var_dump($mapped);
array(32) {
["Age: "]=> string(137) "21 Years. "
["Ethnicity: "]=> string(122) "Caucasian "
["Location: "]=> string(152) "Paris, France "
}
The problem is I don't get any results with: echo $mapped["Age: "];
I have tried:
echo $mapped["Age: "]; // No results
echo $mapped["Age:"]; // No results
echo $mapped[" Age: "]; // No results
echo $mapped['Age: ']; // No results
echo $mapped['Age:']; // No results
var_dump($mapped["Age: "]); // result: NULL
What am I doing wrong? I want echo $mapped["Age: "]; to result: 21 Years
Thank you for your help
Cybrog, white spaces are creating problem for you. Try the code below to remove the white space and access any element without any extra effort.
$keys = str_replace( ' ', '', array_keys($mapped) );
$values = array_values($mapped);
$mapped = array_combine($keys, $values);
var_dump($mapped);
try this one to remove html
$keys = array_map("trim", array_map("strip_tags", array_keys($mapped)));
$values = array_map("trim", array_map("strip_tags", array_values($mapped)));
$mapped = array_combine($keys, $values);
var_dump($mapped);