Hello i am trying to convert PHP serialize strings into comma separated values for a absolutely absurd client requirement :P Here's the code!!!
$o = [1,2,3,4,5,6];
$l = serialize($o);
$o = [$l,$l,$l];
echo '<pre>';
$m = array();
print_r($o);
echo '-----------------------------------' . '<br>';
for($i=0;$i<count($o);$i++)
{
$d = unserialize($o[$i]);
$y = '';
for($q=0;$q<count($d);$q++)
{
$r = $d[$q] ;
$y = $y.$r.',';
//echo $r . ',';
}
//echo $y;
array_push($m,$y);
//echo '<br>';
}
print_r($m);
If I were your, I would use implode to serialize strings into comma separated values.
I've modified you code to this:
$o = array(1,2,3,4,5,6);
$l = serialize($o);
$o = array($l,$l,$l);
echo '<pre>';
$m = array();
print_r($o);
echo '-----------------------------------' . '<br>';
for($i=0;$i<count($o);$i++)
{
$d = unserialize($o[$i]);
// using implode for briefer
$m[] = implode(',', $d);
}
print_r($m);
Related
I have a main array containing the following arrays
(at least 50 different types) :
I'm currently programming in php but i can probably adapt the same functions in java , c# etc...
array('type'=>'x-y','value'=>'12');
array('type'=>'y-z','value'=>'6');
array('type'=>'y-x','value'=>'56');
array('type'=>'z-x','value'=>'19');
array('type'=>'z-y','value'=>'18');
array('type'=>'x-z','value'=>'67');
........
I want to create and traverse a graph for each key and run operations on them e.g :
x-y-z-x : 12 * 6 * 19
x-y-x : 12 * 56
x-z-x : 67 * 19
y-z-y : 6 * 18
.......
I have been trying to run each independently using foreach loops but it won't work for the size of dataset that i have .
Any help would be greatly appreciated. Thanks
The code is in php as required, you can test it as well..
function initData($final, $paths, $values) {
for($i=0; $i<sizeof($final);$i++) {
$path = explode('-', $final[$i]["type"]);
$value = $final[$i]["value"];
array_push($paths, $path);
array_push($values, $value);
}
return [$paths, $values];
}
function getFinalValue($finalPath, $paths, $values) {
$path = explode('-', $finalPath);
$finalValue = 1;
for($i=0;$i<sizeof($path)-1;$i++) {
$stop = $path[$i+1];
$start = $path[$i];
$smallPath = array($start, $stop);
$finalValue *= getValue($smallPath, $paths, $values);
}
return $finalValue;
}
function getValue($smallPath, $paths, $values) {
$value = 0;
for($i=0; $i<sizeof($paths);$i++) {
if($smallPath[0] == $paths[$i][0])
{
if($smallPath[1] == $paths[$i][1]) {
print_r($smallPath);
echo ' ';
$value = $values[$i];
print_r($value);
echo '<br>';
}
}
}
return $value;
}
//Test
function test() {
$a = array('type'=>'x-y','value'=>'12');
$b = array('type'=>'y-z','value'=>'6');
$c = array('type'=>'y-x','value'=>'56');
$d = array('type'=>'z-x','value'=>'19');
$e = array('type'=>'z-y','value'=>'18');
$f = array('type'=>'x-z','value'=>'67');
$paths = [];
$values = [];
$testString = 'x-y-z';
$final = array($a,$b,$c,$d,$e,$f);
$data = initData($final, $paths, $values);
$paths = $data[0];
$values = $data[1];
for ($i=0;$i<sizeof($paths);$i++) {
print_r($paths[$i]);
print_r($values[$i]);
echo '<br>';
}
echo '<br>';
echo '<br>';
$finalValue = getFinalValue($testString, $paths, $values);
echo $testString . '=' . $finalValue;
}
test();
?>
I have string and I want to splitt it to array and remove a specific part and then convert it back to a string .
$string = "width,100;height,8600;block,700;narrow,1;"
I want to search block in this string and remove it with its value "block,700;" and get the string as "width,100;height,8600;narrow,1;"
below is my code php which i tried.Please advice me
$outerARR = explode(";", $string);
$arr = array();
foreach ($outerARR as $arrvalue) {
$innerarr = explode(",", $arrvalue);
$arr[] = $innerarr;
}
for ($i = 0; $i < count($arr); $i++) {
if (in_array($arr, 'block')) {
unset($arr[$i]);
}
}
Please note that "block" in aboive string will not always contain and the value may differ. So I can't use string replace . please advice
You essentially want to replace part of your string:
$string = "width,100;height,8600;block,700;narrow,1;";
$regex = '#(block,(.*?);)#';
$result = preg_replace($regex, '', $string);
echo $result;
Try this:
$string = "width,100;height,8600;block,700;narrow,1;"
$outerARR = explode(";", $string);
$arr = array();
foreach ($outerARR as $arrvalue) {
$innerarr = explode(",", $arrvalue);
$arr[$innerarr[0]] = $innerarr[1];
}
if (array_key_exists('block', $arr)) {
unset($arr['block']);
}
I have a string like
$totalValues ="4565:4,4566:5,4567:6";
Now i want only values after ':' with coma separated ,i.e i want string like $SubValues = "4,5,6"
Thanks
using array_map, implode and explode
$totalValues ="4565:4,4566:5,4567:6";
echo implode(',',array_map(function($val){
$val = explode(':',$val);
return $val[1];
},explode(',',$totalValues)));
try this code it is working
<?php
$str="4565:4,4566:5,4567:6";;
$data =explode(",", $str);
echo '<pre>';
print_r($data);
$newstring="";
foreach ($data as $key => $value) {
preg_match('/:(.*)/',$value,$matches);
$newstring.=$matches[1].",";
}
echo rtrim($newstring,",");
Output
i have updated my code please check it
<?php
$str="4565:4,4566:5,4567:6";
$data1=explode(",", $str);
$newstring1="";
foreach ($data1 as $key1 => $value) {
preg_match('/(.*?):/',$value,$matches);
$newstring1.=$matches[1].",";
}
echo rtrim($newstring1,",");
you might want it this way:
$totalValues ="4565:4,4566:5,4567:6";
$temp = explode(':', $totalValues);
$subValues = $temp[1][0];
$x = count($temp);
for ($i = 2; $i < $x; $i++) {
$subValues .= ',' . $temp[$i][0];
}
echo $subValues;
$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);
I know this question has with out any doubt been asked a whole lot of times. I though can seem to find a solution. So forgive me if it's way to simple.
The question is how do access the end of a while loop.
E.g.
while($countByMonth = mysql_fetch_array($countByMonthSet)) {
$c = $countByMonth["COUNT(id)"];
echo $c . "," ;
}
How do I manage separate each value of the while loop by a comma but of course I don't want the comma at the end of the value.
In advance thank you very much for your help :)
You can:
1) Build a string, and remove the last character:
$c = '';
while ($countByMonth = mysql_fetch_array($countByMonthSet)) {
$c .= $countByMonth["COUNT(id)"] . ',';
}
$c = substr($c, 0, -1);
echo $c;
2) Build an array and use implode()
$c = array();
while ($countByMonth = mysql_fetch_array($countByMonthSet)) {
$c[] = $countByMonth["COUNT(id)"];
}
echo implode(',', $c);
Tip: You can use aliases in your query, like: SELECT COUNT(id) as count FROM .... Then you can access it as $countByMonth['count'], which looks cleaner IMO.
The simple1 solution:
$isFirst = true;
while($countByMonth = mysql_fetch_array($countByMonthSet)) {
$c = $countByMonth["COUNT(id)"];
if ($isFirst) {
$isFirst = false;
} else {
echo = ', ';
}
echo $c;
}
Alternatively, you could implode() the values. Or - perhaps easier to read/understand/maintain - concatenate it all into a string and remove the last "," (SO eats my whitespace; the string is comma-whitespace):
$list = '';
while($countByMonth = mysql_fetch_array($countByMonthSet)) {
$c = $countByMonth["COUNT(id)"];
$list .= $c . ', ';
}
echo substring($list, 0, -2); // Remove last ', '
(Several other answers propose the use of an accumulated array and then use implode(). From a performance perspective this method will be superior to string concatenation.)
1 See comments.
Alternatively you can do:
$arr = array();
while($countByMonth = mysql_fetch_array($countByMonthSet)) {
$arr[] = $countByMonth["COUNT(id)"];
}
echo implode(', ',$arr);
Or afterwards just trim it off with rtrim($c, ',')
While I think the implode solution is probably best, in situations where you can't use implode, think of the basic algorithm differently. Rather than "how can I add a comma behind every element but the last?" ask yourself "how can I add a comma before every element but the first?"
$str = '';
$count = count( $array );
if( $count ) {
$i = 0;
$str = $array[$i];
$i++;
while( i < $count ) {
$str .= ','.$array[$i];
$i++;
}
}
If you "shift" the first element, then you can use a foreach loop:
$str = '';
if( count( $array ) ) {
$str = array_shift( $array );
foreach( $array as $element ) {
$str .= ', '.$element;
}
}
Ty this:
int count;//
while(i)
{
count=i;
}