Grouping in PHP using a character - php

I have an array like:
array{
0 => string 'B.E - ECE',
1 => string 'B.E - EEE',
2 => string 'Msc - Maths',
3 => string 'Msc - Social',
}
So how can I make the array into groups like:
B.E. => ECE, EEE
Msc => Maths,Social
?
I want to do it in PHP. Can anybody help me how to achieve it ?

So is your array split by the "-" character?
so it's Key - Value pairs split by commas?
Ok -
(edit: section removed to clarify answer)
Following conversation and some rearrangement of the question, a second try at a solution, with the above assumptions, try this:
$array = array {
0 => string 'B.E - ECE' (length=9)
1 => string 'B.E - EEE' (length=9)
2 => string 'Msc - Maths' (length=11)
3 => string 'Msc - Social' (length=12)
}
foreach ($array as $row){
$piece = explode("-",$row);
$key = $piece[0];
$newArray[$key][] = $piece[1];
unset($piece);
}
unset($row) ///tidy up
This will output two arrays each of two arrays:
$newArray[Msc] = array("Maths","Social");
$newArray[B.E] = array("ECE","EEE");
What I did was cause the Foreach loop to automatically add onto the array if the key exists with $newArray[$key][] so that the values are automatically collected by key, and the key is defined as the first half of the original array values.
Printing:
To print the result:
foreach($newArray as $key=>$newRow){
/// there are two rows in this case, [B.E] and [MSc]
print $key.":<br>";
print "<pre>";
///<pre> HTML tag makes output use linebreaks and spaces. neater.
print_r($newRow);
///alternatively use var_dump($newRow);
print "</pre>";
}
Alternatively if you wish to print a known named variable you can write:
print_r($newArray['B.E']);
Which will print all the data in that array. print_r is very useful.

what you want is php's explode. Not sure if this will give you the perfect answer but should give you an idea of what to do next.
$groupedArray = array();
foreach($array as $row){
$split = explode(" - ",$row);
$groupedArray[] = $split[0];
}
array_unique($groupedArray); //This will give you the two groupings
foreach($array as $row){
$split = explode(" - ",$row);
$pos = array_search($split[0],$groupedArray);
if($pos !== FALSE){
$groupedArray[$pos][] = $split[1];
}
}
This should give you a full formatted array called $groupedArray where $array is the array you already have.
Hope this helps!

Related

Better way to convert string with multiple spaces into array [duplicate]

This question already has answers here:
How can I explode a string by more than one space, but not by exactly one space in php
(2 answers)
Closed 8 months ago.
I am reading from files and each line has multiple spaces. Example:
$line = 'Testing Area 1 10x10';
I need to convert it into array with 3 elements only so I can save it to a table. Final output should be like this:
$final_array = array('Testing Area', '1', '10x10');
This is how I'm doing it so far:
// read by line
foreach(explode(PHP_EOL, $contents) as $line) {
// split line by 2 spaces coz distance between `1` and `10x10` is atleast 2 spaces
$arr = explode(' ', $line);
// But because `Testing Area` and `1` has so many spaces between them,
// exploding the $line results to empty elements.
// So I need to create another array for the final output.
$final_array = array();
// loop through $arr to check if value is empty
// if not empty, push to $final array
foreach ($arr as $value) {
if (!empty($value)) {
array_push($final_array, $value);
}
}
// insert into table the elements of $final_array according to its column
}
Is there a better way to do this instead of looping through the array and checking each element if it's empty?
Take note that I have multiple files to read, each containing atleast 200 lines like that.
Use preg_split(), with 2 or more spaces as the delimiter.
$array = preg_split('/\s{2,}/', $line);
Assuming the criteria for splitting be two or more spaces, we can try using preg_split here:
$line = 'Testing Area 1 10x10';
$final_array = preg_split("/\s{2,}/", $line);
print_r($final_array);
This prints:
Array
(
[0] => Testing Area
[1] => 1
[2] => 10x10
)

how do i get data from csv and put in variable and get only the value that i want

Example
I have CSV file that contains data of random number example data in CSV :
639123456789,73999999999,739222222222,839444444444,8639555555555....more
So, if I upload it, I want it to explode in a variable or in an array as long as I get the specific data. example of data I want to get is all 2 first line starting at 73 be extract so meaning all numbers that start with 73 only.
Example: 73999999999,739222222222
I have tried it by using only 1 number using split,substr and explode function but my problem is if the user input a CSV bulk data with no limit.
You can use substr() and loop through your array deleting the elements that do not match.
$str = '639123456789,73999999999,739222222222,839444444444,8639555555555';
$array = explode(',', $str); //Convert your string to an array.
$searchString = '73'; //Set the value your looking for.
foreach($array as $key=>$value){
if(substr($value, 0, 2) != $searchString){ //This will test first two characters.
unset($array[$key]);
}
}
$array = array_values($array);
print_r($array);
This will output:
Array
(
[0] => 73999999999
[1] => 739222222222
)
Updated
This will make a new array with only the numbers you want in it, leaving the original array untouched.
$str = '639123456789,73999999999,739222222222,839444444444,739222222222,839444444444,839444444444,73999999999';
$array = explode(',', $str);
$searchString = '73';
foreach($array as $key=>$value){
if(substr($value, 0, 2) == $searchString){
$results[] = $value;
}
}
print_r($results);

merging two elements of two arrays in php

Hello Everyone I have a Array in php like
array (size=2)
0 => string 'A6,A5,B12,B11,' (length=14)
1 => string 'B6,B5,B8,B7,' (length=12)
on var_dump($arr). How could I convert it to something like
array('A6,A5,B12,B11,B6,B5,B8,B7,')
in php.
here is what i'm doing eaxctly to get the above array
$id= "1";
$data['busInfo']= $this->dashboard_model->find_bus($id);
$data['reservationInfo'] = $this->dashboard_model->get_booked_seats_info($id);
$arr =array();
foreach ($data['reservationInfo'] as $reserved){
$seatBooked = $reserved->seats_numbers;
array_push($arr, $seatBooked);
}
var_dump($arr);
I'm using Codeigniter as my framework.
You can just append to a string, then create a single element array with that string (if you actually need an array):
$data['reservationInfo'] = $this->dashboard_model->get_booked_seats_info($id);
$str='';
foreach ($data['reservationInfo'] as $reserved){
$str .= $reserved->seats_numbers;
}
var_dump(array($str));
Or just implode the source array:
var_dump(array(implode('', $this->dashboard_model->get_booked_seats_info($id))));

Creating a dynamic PHP array

I am new PHP question and I am trying to create an array from the following string of data I have. I haven't been able to get anything to work yet. Does anyone have any suggestions?
my string:
Acct_Status=active,signup_date=2010-12-27,acct_type=GOLD,profile_range=31-35
I want to dynamically create an array called "My_Data" and have id display something like my following, keeping in mind that my array could return more or less data at different times.
My_Data
(
[Acct_Status] => active
[signup_date] => 2010-12-27
[acct_type] => GOLD
[profile_range] => 31-35
)
First time working with PHP, would anyone have any suggestions on what I need to do or have a simple solution? I have tried using an explode, doing a for each loop, but either I am way off on the way that I need to do it or I am missing something. I am getting something more along the lines of the below result.
Array ( [0] => Acct_Status=active [1] => signup_date=2010-12-27 [2] => acct_type=GOLD [3] => profile_range=31-35} )
You would need to explode() the string on , and then in a foreach loop, explode() again on the = and assign each to the output array.
$string = "Acct_Status=active,signup_date=2010-12-27,acct_type=GOLD,profile_range=31-35";
// Array to hold the final product
$output = array();
// Split the key/value pairs on the commas
$outer = explode(",", $string);
// Loop over them
foreach ($outer as $inner) {
// And split each of the key/value on the =
// I'm partial to doing multi-assignment with list() in situations like this
// but you could also assign this to an array and access as $arr[0], $arr[1]
// for the key/value respectively.
list($key, $value) = explode("=", $inner);
// Then assign it to the $output by $key
$output[$key] = $value;
}
var_dump($output);
array(4) {
["Acct_Status"]=>
string(6) "active"
["signup_date"]=>
string(10) "2010-12-27"
["acct_type"]=>
string(4) "GOLD"
["profile_range"]=>
string(5) "31-35"
}
The lazy option would be using parse_str after converting , into & using strtr:
$str = strtr($str, ",", "&");
parse_str($str, $array);
I would totally use a regex here however, to assert the structure a bit more:
preg_match_all("/(\w+)=([\w-]+)/", $str, $matches);
$array = array_combine($matches[1], $matches[2]);
Which would skip any attributes that aren't made up of letters, numbers or hypens. (The question being if that's a viable constraint for your input of course.)
$myString = 'Acct_Status=active,signup_date=2010-12-27,acct_type=GOLD,profile_range=31-35';
parse_str(str_replace(',', '&', $myString), $myArray);
var_dump($myArray);

Creating menu from Text

I am very new to PHP programming and dont know the exact syntax of various labrary functions like , split, find ,etc.
I am having following text with me
in a string variable
$menu = '/home-page|HOME
/our-iphone-app|OUR iPhone APP
/join-us|JOIN ME
/contact-us|CONTACT US';
I want to populate to arrays with this text one array containing the portion before the pipe | and second array contains portions after pipe. How to do this using some split by char(|) method.
Finally arrays must contain
$arraypage = {'0'->'/home-page','1'->'/our-iphone-app'} // etc, and...
$arrayTitle = {'0'->'HOME','2'->'OUR iPhone App'} // etc
You need to break up the string by new lines and then by pipe characters.
$lines = explode("\n", $menu);
$arraypage = array();
$arrayTitle = array();
foreach($lines as $line) {
list($arraypage[], $arrayTitle[]) = explode('|', $line);
}
var_dump of the resulting arrays gives:
array
0 => string '/home-page' (length=10)
1 => string '/our-iphone-app' (length=15)
2 => string '/join-us' (length=8)
3 => string '/contact-us' (length=11)
array
0 => string 'HOME' (length=4)
1 => string 'OUR iPhone APP' (length=14)
2 => string 'JOIN ME' (length=7)
3 => string 'CONTACT US' (length=10)
$array = explode("\n", $array);
$result1 = array();
$resutl2 = array();
foreach($array as $arr){
$temp = explode('|', $arr);
$result1[] = $temp[0];
$result2[] = $temp[1];
}
I'd suggest you make your string contain another separator like so:
$menu = '/home-page|HOME:/our-iphone-app|OUR iPhone APP:/join-us|JOIN ME:/contact-us|CONTACT US';
Then you can use the explode method to split up your string to an associative array.
$array = explode(":", $menu);
foreach($array as $key => $val) {
$array[$key] = explode("|", $val);
}
I'd probably just define the data in an array to start with, rather than as a string. I'd also build it in the format
$menu_array = {
{'url'=>'/home-page','text'=>'HOME'},
{'url'=>'/our-iphone-app','text'=>'OUR iPhone APP'},
{'url'=>'/join-us','text'=>'JOIN ME'},
{'url'=>'/contact-us','text'=>'CONTACT US'},
};
Since that's almost certainly going to be more useful for whatever you do with it next.
If you do need to use a string for some reason though, I'd say a regular expression is the tidiest way to do this. The following:
preg_match_all('/^(?P<url>[^|]+)\\|(?P<text>\\V+)\\v*$/m',$menu,$menu_array,PREG_SET_ORDER)
would set $menu_array to the format I used above.
In fairness, using a regular expression for this may be a little overkill, but I prefer the power of regexes, which are easier to tweak later when you want to add things than loops of explode()s.

Categories