Extracting a specific part of a string - php

I have this string:
[25-03-15, 1236], [26-03-15, 3000], [27-03-15, 3054], [30-03-15, 4000]
I want to get two parts from it as below:
['25-03-15','26-03-15','27-03-15','30-03-2015']
and
[1236,3000,3054,4000]
Please guide me how I can perform this task.
PS: I am working of view page of codeigniter.
I'm getting the first thing as:
<?php
$usd=$this->db->query('select transaction_date, SUM(amount) as total
from transactions GROUP BY transaction_date')->result_array();
$str = '';
for($i=0; $i<count($usd); $i++){
if($i!=0){
$str = $str.', ['.date('d-m-y', strtotime($usd[$i]["transaction_date"])).', '.$usd[$i]["total"].']';
}else{
$str = $str.'['.date('d-m-y', strtotime($usd[$i]["transaction_date"])).', '.$usd[$i]["total"].']';
}
}
echo $str;
?>

Try this..
$date = '';
$total = '';
for($i=0; $i<count($usd); $i++){
if($i!=0){
$date .= date('d-m-y', strtotime($usd[$i]["transaction_date"])).', ';
$total .= $usd[$i]["total"].', ';
}else{
$date .= date('d-m-y', strtotime($usd[$i]["transaction_date"])).', ';
$total .= $usd[$i]["total"].', ';
}
}
echo $finaldate='['. $date.']';
echo $finaltotal='['. $total.']';

I don't see any reason why you need to save this data from your db in a string. Just save it in an array and it is that easy:
So here I save your data in an array, so that you get this structure:
array(
array(25-03-15, 1236),
array(26-03-15, 3000),
array(27-03-15, 3054),
array(30-03-15, 4000)
)
The you can simply use array_column() to extract the single columns, like this:
<?php
$usd = $this->db->query('select transaction_date, SUM(amount) as total
from transactions GROUP BY transaction_date')->result_array();
foreach($usd as $k => $v)
$result[] = [date('d-m-y', strtotime($usd[$k]["transaction_date"])), $usd[$k]["total"]];
$partOne = array_column($result, 0);
$partTwo = array_column($result, 1);
?>
Also if you then need this data in a string as you said in the comments you can simply transform it:
I will pass this extracted data to a graph that accepts this kind of data – Shahid Rafiq 6 mins ago
Just use this:
echo $str = "[" . implode("],[", array_map(function($v){
return implode(",", $v);
}, $usd)) . "]";
output:
[25-03-15, 1236], [26-03-15, 3000], [27-03-15, 3054], [30-03-15, 4000]
EDIT:
If you also want the parts as string just simply do this:
$partOne = "[" . implode("],[", array_column($arr, 0)) . "]";
$partTwo = "[" . implode("],[", array_column($arr, 1)) . "]";
output:
[25-03-15],[26-03-15],[27-03-15],[30-03-15]
[1236],[3000],[3054],[4000]

Related

Using preg_grep to find match

I need server to return complete IDs that contain an integer(single digit or more) sent in by a user to find a match.
e.g I submit '5678', then server returns 12567891, 54356782, 90567811.
Emphasis on '5678'. My code returns no results.
<?php
$per = array(456755643, 78567561, 443321, 33267554560, 44321122, 554367533, 3390);
$thr = 675;
if(isset($_POST['search'])){
$jake = preg_grep(("/$thr+/", $per);
foreach($jake as $value){
print $value . br;
}
}
?>
try this
$per = array(456755643, 78567561, 443321, 33267554560, 44321122, 554367533, 3390);
$thr = 675;
$jake = preg_grep("/$thr/", $per);
foreach($jake as $value){
print $value . '<br>';
}
//result
456755643
78567561
33267554560
554367533

PHP - Searching words in a .txt file

I have just learnt some basic skill for html and php and I hope someone could help me .
I had created a html file(a.html) with a form which allow students to input their name, student id, class, and class number .
Then, I created a php file(a.php) to saved the information from a.html into the info.txt file in the following format:
name1,id1,classA,1
name2,id2,classB,24
name3,id3,classA,15
and so on (The above part have been completed with no problem) .
After that I have created another html file(b.html), which require user to enter their name and id in the form.
For example, if the user input name2 and id2 in the form, then the php file(b.php) will print the result:
Class: classB
Class Number: 24
I have no idea on how to match both name and id at the same time in the txt file and return the result in b.php
example data:
name1,id1,classA,1
name2,id2,classB,24
name3,id3,classA,15
<?php
$name2 = $_POST['name2'];
$id2 = $_POST['id2'];
$data = file_get_contents('info.txt');
if($name2!='')
$konum = strpos($data, $name2);
elseif($id2!='')
$konum = strpos($data, $id2);
if($konum!==false){
$end = strpos($data, "\n", $konum);
$start = strrpos($data, "\n", (0-$end));
$row_string = substr($data, $start, ($end - $start));
$row = explode(",",$row_string);
echo 'Class : '.$row[2].'<br />';
echo 'Number : '.$row[3].'<br />';
}
?>
Iterate through lines until you find your match. Example:
<?php
$csv=<<<CSV
John,1,A
Jane,2,B
Joe,3,C
CSV;
$data = array_map('str_getcsv', explode("\n", $csv));
$get_name = function($number, $letter) use ($data) {
foreach($data as $row)
if($row[1] == $number && $row[2] == $letter)
return $row[0];
};
echo $get_name('3', 'C');
Output:
Joe
You could use some simple regex. For example:
<?php
$search_name = (isset($_POST['name'])) ? $_POST['name'] : exit('Name input required.');
$search_id = (isset($_POST['id'])) ? $_POST['id'] : exit('ID input required.');
// First we load the data of info.txt
$data = file_get_contents('info.txt');
// Then we create a array of lines
$lines = preg_split('#\\n#', $data);
// Now we can loop the lines
foreach($lines as $line){
// Now we split the line into parts using the , seperator
$line_parts = preg_split('#\,#', $line);
// $line_parts[0] contains the name, $line_parts[1] contains the id
if($line_parts[0] == $search_name && $line_parts[1] == $search_id){
echo 'Class: '.$line_parts[2].'<br>';
echo 'Class Number: '.$line_parts[3];
// No need to execute the script any further.
break;
}
}
You can run this. I think it is what you need. Also if you use post you can change get to post.
<?php
$name = $_GET['name'];
$id = $_GET['id'];
$students = fopen('info.txt', 'r');
echo "<pre>";
// read each line of the file one by one
while( $student = fgets($students) ) {
// split the file and create an array using the ',' delimiter
$student_attrs = explode(',',$student);
// first element of the array is the user name and second the id
if($student_attrs[0]==$name && $student_attrs[1]==$id){
$result = $student_attrs;
// stop the loop when it is found
break;
}
}
fclose($students);
echo "Class: ".$result[2]."\n";
echo "Class Number: ".$result[3]."\n";
echo "</pre>";
strpos can help you find a match in your file. This script assumes you used line feed characters to separate the lines in your text file, and that each name/id pairing is unique in the file.
if ($_POST) {
$str = $_POST["name"] . "," . $_POST["id"];
$file = file_get_contents("info.txt");
$data = explode("\n", $file);
$result = array();
$length = count($data);
$i = 0;
do {
$match = strpos($data[$i], $str, 0);
if ($match === 0) {
$result = explode(",", $data[$i]);
}
} while (!$result && (++$i < $length));
if ($result) {
print "Class: " . $result[2] . "<br />" . "Class Number: " . $result[3];
} else {
print "Not found";
}
}

DB Array to expected javascript format

I am implementing Highcharts in my application. It needs data in specific format.
The data in my table is as follows
The javascript needs data in below format
When I var_dump my x_axis array and y_axis array, I get below result
Which php functions should I use to format my array elements and pass to that JavaScript in that format?
data:[
[<? echo PHP_some_function(" ' ", x_axis) ?>, <? echo (y_axis) ?>] //quotes for x, no quotes for y value
] //Moreover it should run for all the values in x_axis and y_axis
I need some logic here..
My final graph would look like
The problem is your query.
It should be like the following.
SELECT x_axis, y_axis FROM yourTableName;
This way you'll get exactly the format that Highcharts needs. You just have to insert it inside an array.
Assuming:
$x_axis = array('Safari', 'Opera', 'Firefox', 'IE', 'Chrome', 'Others');
$y_axis = array(10, 6, 40.5, 20, 10.6, 0.5);
This should work:
$data = array();
$length = count($x_axis);
for ($i = 0; $i < $length; $i++) {
$data[] = array($x_axis[i], $y_axis[i]);
}
[<? echo "'". json_encode($x_axis). "', " . json_encode($y_axis) ?>]
Demo: http://codepad.org/G5JAtXWu
Nix that I was confused.
What you want to do is this:
foreach($x_axis as $key=>$x) {
echo "['" . $x . "', " . $y_axis[$key] . "]";
}
Demo: http://codepad.org/SKNk1VaX
To wrap it all up:
$d = array();
foreach($x_axis as $key=>$x) {
$d[] = "['" . $x . "', " . $y_axis[$key] . "]";
}
echo json_encode($d);
Demo: http://codepad.org/KhofwXCi
probably array combine and than json encode and replace? just in case for diversity;)
<?php
$x_axis = array(
'Safari', 'Opera', 'fireFox'
);
$y_axis = array(
10, 30.4, 50
);
$keyFilled = array_combine($x_axis, $y_axis);
arsort($keyFilled);
$jsonData = json_encode($keyFilled);
$jsonDataReplaced = str_replace(array(',', '{', '}', ':'), array('],[', '[', ']', ','), $jsonData);
echo '<pre>';
var_dump('['.$jsonDataReplaced.']');
?>
output is:
string(45) "[["fireFox",50],["Opera",30.4],["Safari",10]]"
http://phpfiddle.org/main/code/jq4-cgb

php string in to javascript code with comma except last string

I'm using a javascript plugin this is the line which I need help from u
<script type="text/javascript">
$('ul#news').newswidget({ source: ['http://rss.news.yahoo.com/rss/us', 'http://rss.news.yahoo.com/rss/world', 'http://feeds.bbci.co.uk/news/rss.xml'],
I would like to add URL data from MySQL
I'm using it with while loop like this
$('ul#news').newswidget({ source:[<?php
while($rssrow = mysql_fetch_array($rss))
{
echo "'"."$rssrow[rss_name]"."'".",";
}
?>],
It doesn't work properly :(.
I need to get like URL,URL,RUL like this.
that means no comma for the last one
any one please help me
You can actually do that pretty easily by a simple reorganization:
if($rssrow = mysql_fetch_array($rss))
{
echo "'".$rssrow['rss_name']."'";
while($rssrow = mysql_fetch_array($rss))
{
// note no quotes -- they are redundant
// prepend the comma
echo ","."'".$rssrow['rss_name']."'";
}
}
It does make for an extra step for the reader, but it does have the benefit of not needing substring, a new array, or a flag.
You could just build the string and remove the last comma:
$result = '';
while($rssrow = mysql_fetch_array($rss))
{
$result .= "'"."$rssrow[rss_name]"."'".",";
}
echo ($result != '') ? substr($result, 0, -1) : "''";
OR use implode():
$result = array();
while($rssrow = mysql_fetch_array($rss))
{
$result[] = $rssrow[rss_name];
}
echo "'" . implode($result, "','") . "'";
(both of these methods will output '' if the result set is empty.)
$urls = "";
while($rssrow = mysql_fetch_array($rss))
{
$urls.= "'$rssrow[rss_name]',";
}
echo substr($urls, 0, -1);
I wonder why no comment points out that you should definitely escape your output. If an entry contains a ', all solutions aside from Dmitry F’s first will break badly.
$('ul#news').newswidget({ source:[<?php
$arr = array();
while($rssrow = mysql_fetch_array($rss))
{
$arr[] = '"' . str_replace('"', '\"', $rssrow['rss_name']) . '"';
}
echo implode(',', $arr);
?>],
here is a little bit different approach:
<?php
$news = array(
'source' => array(
'http://example.com',
'http://example.com'
)
);
$news_json = json_encode($news);
?>
<script>
$('ul#news').newswidget(<?php echo $news_json; ?>);
</script>
another variation:
$url = array();
while($rssrow = mysql_fetch_array($rss))
{
$url[] = '"' . $rssrow['rss_name'] . '"';
}
echo implode(',', $url);

PHP to form string like "A, B, C, and D" from array values

Given the following array:
Array
(
[143] => Car #1
[144] => Car #2
[145] => Car #3
)
I am currently using this
implode(', ', array_values($car_names))
to generate a string like
Car #1, Car #2, Car #3
I would like to actually get something like
Car #1, Car #2 and Car #3
The idea would be to insert " and " between the two last elements of the array.
If the array happens to contain two key/value pairs (eg, user has 2 cars), there would be no commas.
Car #1 and Car #2
And if the array contains one key/value (eg, user has 1 car)
Car #1
Any suggestion how to get this done? I tried using array_splice but I'm not sure that's the way to go (ie, inserting a new element into the array).
Thanks for helping!
$last = array_pop($car_names);
echo implode(', ', $car_names) . ' AND ' . $last;
I think you probably want something like this, using array_pop to get the last element off the end of the array. You can then implode the rest of the array, and add the last element in a custom fashion:
$last_value = array_pop($car_names);
$output = implode(', ', array_values($car_names));
$output .= ($output ? ' and ' : '') . $last_value;
Edit: added conditional to check if the array had only one element.
A preg_replace can look for the last command just just swap it to an and
$yourString = preg_replace( "/, ([\w#]*)$/", "and \1", $yourString );
This solution is a bit longer, but tested for all array sizes and it is a complete solution. Also, it doesn't modify the array like the above answers and is separated into a function.
function arrayToString($arr) {
$count = count($arr);
if ($count <= 2) {
return implode(' and ', $arr);
}
$result = '';
$i = 0;
foreach ($arr as $item) {
if ($i) $result .= ($i == $count - 1) ? ' and ' : ', ';
$result .= $item;
$i++;
}
return $result;
}
Compacted version with ugly formatting and ignoring good practices like initializing variables:
function arrayToString($arr) {
if (count($arr) <= 2) return implode(' and ', $arr);
foreach ($arr as $item) {
if ($i) $result .= ($i == count($arr) - 1) ? ' and ' : ', ';
$result .= $item; $i++;
}
return $result;
}
I'm not sure there's a built in function for this, but something like this should work.
$last = $car_names[count($car_names)-1];
$implodedString = implode(', ', array_values($car_names))
$implodedString = str_replace(", $last", "and $last", $implodedString);
That's an example with the functions named in my comment above:
strrpos() - Find the position of the last occurrence of a substring in a string
substr() - Return part of a string
and the code:
$text = implode(', ', array_values($car_names));
$last = strrpos($text, ',');
if ($last) $text = substr($text, 0, $last-1) . ' AND ' . substr($text, $last+1);
echo $text;
There are a number of ways you could do this. Here's another.
<?php
$cars = array('Car #1', 'Car #2', 'Car #3', 'Car #4');
$car = array('Car #1');
$twocars = array('Car #1', 'Car #2');
function arrayToText($arr) {
switch (count($arr)) {
case 1:
return $arr[0];
break;
case 2:
return implode($arr, ' and ');
break;
default:
$last = array_pop($arr);
return implode($arr, ', ') . ' and ' . $last;
break;
}
}
echo '<p>' . arrayToText($cars) . "</p>\n";
echo '<p>' . arrayToText($twocars) . "</p>\n";
echo '<p>' . arrayToText($car) . "</p>\n";
Output
<p>Car #1, Car #2, Car #3 and Array</p>
<p>Car #1 and Car #2</p>
<p>Car #1</p>

Categories