How to sort an array-like variable? - php

I am adding the names of regions to a a variable using the below code (shortened). Everything works as intended, except for the sort function which throws an error saying that it requires an array instead of a string.
How can I still manage to sort the content of my variable alphabetically ?
$regions = '';
$countR = 1;
foreach ($objR->days as $days) {
if($days->dateMatch == "Yes" && !empty($days->regions)) {
foreach(explode(',', $days->regions) as $r){
$regions .= str_replace(" / ", ", ", $r)) . "<br />";
$countR++;
}
}
}
sort($regions);

Try this:
You should use array for storage.
$regions = array();
$countR = 1;
foreach ($objR->days as $days) {
if($days->dateMatch == "Yes" && !empty($days->regions)) {
foreach(explode(',', $days->regions) as $r){
$region = str_replace(" / ", ", ", $r)) . "<br />";
array_push($regions,$region);
$countR++;
}
}
}
sort($regions);

Related

How to use strstr() php

I want to cut text in array but I have no idea to cut this
I try strstr() but it not true.
I try
$ff='';
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
$ff .= $row['fav'] . ",";
}
if( strpos( $ff, "_" )) {
$text = strstr($ff, '_');
echo $text;
}
$ff ='A_0089,A_5677,B_4387,A_B_5566,'
I want output show
0089,5677,4387,B_5566,
Here is one example, using substr() with strpos():
$ff='A_0089,A_5677,B_4387,A_B_5566';
$items = explode(',', $ff);
foreach($items as $item) {
echo substr($item, strpos($item, '_')) . "\n";
}
The above code returns:
_0089
_5677
_4387
_B_5566
You're better off not building a string, but building an array. The way you build the string you have a dangling comma, which you do not want.
$ff = array();
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
$ff[] = $row['fav'];
}
foreach($ff as $item) {
echo substr($item, strpos($item, '_')) . "\n";
}
Based on your desire to keep the commas and create a string:
$ff='A_0089,A_5677,B_4387,A_B_5566,';
$items = explode(',', $ff);
foreach($items as $item) {
$new[] = substr($item, strpos($item, '_'));
}
$newFF = implode(',', $new);
echo $newFF;
returns:
_0089,_5677,_4387,_B_5566,
Probably this is what you are looking for
<?php
function test_alter(&$item1)
{
$pattern = '/^[A-Z]{1}[_]{1}/';
$item1 =preg_replace($pattern,"",$item1);
}
$ff="A_0089,A_5677,B_4387,A_B_5566,";
$nff=explode(",",$ff);
array_walk($nff, 'test_alter');
echo implode(",",$nff);
?>

PHP: variable interpolation issue

I am having a real issue with variable interpolation - maybe what I'm trying to do shouldn't be done? Sample code (IRL, the array is 70+ elements):
<form submit>
$_POST['A']; //returns 12
$_POST['B']; //returns 8
<query to get orig field values>
$OrigA = $row->appA; //returns 12
$OrigB = $row->appB; //return 14
<array of names>
$fields = array ("A", "B");
$querystr = "INSERT INTO tblEditHist VALUES ";
foreach ($fields as $field) {
$orig = "Orig" . $field;
$new = "\$_POST['app" . $field . "']";
$fieldname = "app" . $field;
if (${$orig} != ${$new}) { $querystr .= "('default', $applID, '$fieldname', '${$orig}', '${$new}', '$DateTimeReq', '$hvid'), "; };
}
print "querystr: " . $querystr . "\n";
The part if (${$orig} != ${$new}) is what's not working as I would expect. When I print it out to screen with print "DEBUG: if (${$orig} != ${$new}) { $querystr .= \"('default', $applID, '$fieldname', '{$orig}', '{$new}', '$DateTimeReq', '$hvid')\"; };<br />\n";, I see my variables aren't interpolating properly, my debug print says: DEBUG: if ( != ) { .... It should interpolate to (for B): DEBUG: if (8 != 14) { ...
I have tried various combinations of dollar signs and braces, but I don't seem to be making headway. Am I barking up the wrong tree here?
Thanks as always!!
Like this : No interpolation POST variable
<?php
$A = $_POST['A'] = 12; //returns 12
$B = $_POST['B'] = 8; //returns 8
$OrigA = 12; //returns 12
$OrigB = 14; //return 14
$fields = array ("A", "B");
$querystr = "INSERT INTO tblEditHist VALUES ";
foreach ($fields as $field) {
$orig = "Orig" . $field;
$fieldname = "app" . $field;
if (${$orig} != ${$field}) { $querystr .= "('default', $applID, '$fieldname', '${$orig}', '${$new}', '$DateTimeReq', '$hvid'), "; };
}
print "querystr: " . $querystr . "\n";
?>
See http://codepad.org/Ecro0PyG
I don't get all your questions but maybe this code could help you a little (you can use your $_POST var instead of mine $post, that is just to show result and debug):
$post = array();
$post['A'] = 12;
$post['B'] = 8;
$OrigA = 12;
$OrigB = 14;
$fields = array ("A", "B");
$querystr = "INSERT INTO tblEditHist VALUES ";
foreach ($fields as $field) {
$origVarName = 'Orig'.$field;
echo '$$origVarName = '.$$origVarName.'<br/>';
echo '$post[$field] = '.$post[$field].'<br/>';
$fieldname = "app" . $field;
if ($$origVarName != $post[$field]) {
echo $field.' NOT EQUAL!';
} else {
echo $field.' EQUAL!';
}
}

Need to change case of a string - PHP

$variable = "test_company_insurance_llc_chennai_limited_w-8tyu.pdf";
I need to display above the $variable like
Test Company Insurance LLC Chennai Limited W-8TYU.pdf
For that I've done:
$variable = str_replace("_"," ","test_company_insurance_llc_chennai_limited_w-8tyu.pdf");
$test = explode(" ", $variable);
$countof = count($test);
for ($x=0; $x<$countof; $x++) {
if($test[$x] == 'w-8tyu' || $test[$x] == 'llc') {
$test[$x] = strtoupper($test[$x]);
//todo
}
}
I've got stuck in the to-do part.
I will change the specific words to uppercase using strtoupper.
Later, how should I need to merge the array?
Any help will be thankful...
$str_in = "test_company_insurance_llc_chennai_limited_w-8tyu.pdf";
$lst_in = explode("_", $str_in);
$lst_out = array();
foreach ($lst_in as $val) {
switch($val) {
case "llc" : $lst_out[] = strtoupper($val);
break;
case "w-8tyu.pdf" : $lst_temp = explode('.', $val);
$lst_out[] = strtoupper($lst_temp[0]) . "." . $lst_temp[1];
break;
default : $lst_out[] = ucfirst($val);
}
}
$str_out = implode(' ', $lst_out);
echo $str_out;
Not terribly elegant, but perhaps slightly more flexible.
$v = str_replace("_"," ","test_company_insurance_llc_chennai_limited_w-8tyu.pdf");
$acronyms = array('llc', 'w-8tyu');
$ignores = array('pdf');
$v = preg_replace_callback('/(?:[^\._\s]+)/', function ($match) use ($acronyms, $ignores) {
if (in_array($match[0], $ignores)) {
return $match[0];
}
return in_array($match[0], $acronyms) ? strtoupper($match[0]) : ucfirst($match[0]);
}, $v);
echo $v;
The ignores can be removed provided you separate the extension from the initial value.
See the code below. I have printed the output of the code as your expected one. So Run it and reply me...
$variable = str_replace("_"," ","test_company_insurance_llc_chennai_limited_w-8tyu.pdf");
$test = explode(" ", $variable);
$countof = count($test);
for ($x=0; $x<$countof; $x++) {
if($test[$x] == 'llc') {
$test[$x] = strtoupper($test[$x]);
//todo
}elseif($test[$x] == 'w-8tyu.pdf'){
$file=basename($test[$x],'pdf');
$info = new SplFileInfo($test[$x]);
$test[$x] = strtoupper($file).$info->getExtension();
}
else{
$test[$x]=ucfirst($test[$x]);
}
}
echo '<pre>';
print_r($test);
echo '</pre>';
echo $output = implode(" ", $test);

trim() function causes error "expects parameter 1 to be string, array given"

I added a sub array to the below foreach loop. Since then I get the following error which seems to refer to the trim part of my else statement:
Warning: trim() expects parameter 1 to be string, array given in C:\inetpub\wwwroot\calendarCheck\index.php ...
How can I adapt this to make it work with the sub array? Source: Add titles to items from array
My code:
$countries = '';
$valC = '';
$countC = 0;
foreach ($objDays->days as $days) {
if(($days->dateMatch == "Yes") && ($days->locales != "")) {
$inputC[] = array(
"text" => explode(',', $days->locales),
"desc" => $days->desc
);
$countC++;
}
}
if($countC == 0) {
$countries = " <img src='images/icons/emotion_what.png' alt='' /> No data on file for this date.";
} else {
$arrC = array_map("trim", call_user_func_array("array_merge", $inputC));
sort($arrC);
array_walk($arrC, function (&$valC) { $valC = "<img src='images/icons/flags-32/flag_" . str_replace(" ", "_", $valC['text']) . ".png' alt='".$valC['desc']."' id='c" . $valC['text'] . "' style='width:32px' /> " . $valC['text']; } );
$countries = implode(' ', $arrC);
}
// ...
echo $countries;
You could alternatively do it just by building the expected output: (Untested)
<?php
$countries = '';
foreach ($objDays->days as $days) {
if($days->dateMatch == "Yes" && !empty($days->locales)) {
foreach(explode(',', $days->locales) as $text){
$countries .= "
<img src='images/icons/flags-32/flag_".str_replace(" ", "_", $text).".png'
alt='".htmlentities($days->desc)."'
id='c".htmlentities($text)."'
style='width:32px' /> " . htmlentities($days->desc);
}
}
}
if(empty($countries)){
echo " <img src='images/icons/emotion_what.png' alt='' /> No data on file for this date.";
}else{
echo $countries;
}
?>
You can use custom function instead of trim:
$arrC = array_map(function($x) {
$result = array();
foreach ($x as $k => $v)
$result[$k] = trim($v);
return $result;
}, call_user_func_array("array_merge", $inputC));

php replace non matches from two arrays

How do you replace all non matches from one array that are not defined within the other array, i have kind of got working but its not exactly right. as i will show you.
the result is, but wrong.
- - £ 8 - - - - - - - -
The required result should be
£ 8 - -
this is how my code is
$vals_to_keep = array(8, 'y', '£');
$replace_if_not_found = array('£', 8, '#', 't'); // replace if not in above array
$result = '';
foreach ($replace_if_not_found as $d) {
foreach ($vals_to_keep as $ok) {
if(strcmp($d, $ok) == 0){
$result .= $d . " ";
}else
$result .= str_replace($d, $ok ,'-') . " ";
}
}
echo $result;
use in_array http://php.net/manual/en/function.in-array.php
foreach ($replace_if_not_found as $d) {
if (in_array($d, $vals_to_keep))
$result .= $d . " ";
else
$result .= str_replace($d, $ok ,'-') . " ";
}
You could loop over all of the items in $replace_if_not_found replacing them with -, or not, as appropriate.
Using closure in PHP 5.3 or above
$result = array_map(function($item) use ($vals_to_keep) {
return in_array($item, $vals_to_keep, TRUE) ? $item : '-';
}, $replace_if_not_found);
echo implode(' ', $result);
Using a foreach loop
$result = array();
foreach ($replace_if_not_found as $item) {
if (in_array($item, $vals_to_keep, TRUE)) {
$result[] = $item;
} else {
$result[] = '-';
}
}
echo implode(' ', $result;

Categories