PHP explode and put into array - php

I have this line of string
Fruits-banana|apple|orange:Food-fries|sausages:Desserts-ice cream|apple pie
the : (colon) is the separator for the main topic, and the | is the separator for the different type of sub topics.
I tried to explode it out and put it into array, I need the result to be something like this to be displayed in a drop down menu:-
Fruits
banana
apple
orange
Food
fries
sausages
$result=explode(":",$data);
foreach($result as $res) {
$sub_res[]=explode("-",$res);
}
foreach($sub_res as $sub) {
//echo $sub[1]."<br>"; Over here, I can get the strings of [0]=>banana|apple|orange, [1]=>sausages|fries,
// I explode it again to get each items
$items[]=explode("|",$sub[1]);
$mainCategory[]=$sub[0]; // This is ([0]=>Fruits, ]1]=>Food, [2]=>dessert
// How do I assign the $items into respective categories?
}
Thanks!

You can do:
$result=explode(":",$data);
foreach($result as $res) {
$sub = explode("-",$res);
$mainCategory[$sub[0]] = explode("|",$sub[1]);
}
Working link

Code:
$data = "Fruits-banana|apple|orange:Food-fries|sausages:Desserts-ice cream|apple pie";
foreach(explode(":",$data) as $res) { // explode by ":"
$cat = explode("-",$res); // explode by "-"
$ilovefood[$cat[0]] = explode("|",$cat[1]); // explode by "|"
}
print_r($ilovefood);
//Returns : Array ( [Fruits] => Array ( [0] => banana [1] => apple [2] => orange ) [Food] => Array ( [0] => fries [1] => sausages ) [Desserts] => Array ( [0] => ice cream [1] => apple pie ) )
foreach($ilovefood as $type=>$yum){
echo "$type:<select>";
foreach($yum as $tasty){
echo "<option>$tasty</option>";
}
echo "</select>";
}
Updated to reflect the drop-down addition. Looks like I just did your homework, though I'll leave it up to you to combine all the into one foreach loop.

I'd propose an arguably more readable version of codeaddicts' answer
$str = "Fruits-banana|apple|orange:Food-fries|sausages:Desserts-ice cream|apple pie";
$topics = array();
foreach (explode(':', $str) as $topic) {
list($name, $items) = explode('-', $topic);
$topics[$name] = explode('|', $items);
}

Related

displaying items in array ordered by id inside string

I want to display items in an array separately, ordered by groups.
The items are stored in a string like this:
$itemsString = "1:asd, 1:wer, 2:dfg, 3:gfg, 3:sdfss"; //and so forth
Then I display them like this:
$itemsArray = explode(", ", $itemsString);
foreach($itemsArray as $item){
echo substr($item,2); //substr to get rid of the group id
}
EDIT: solution
if(strpos($item, "1:")!==false){
echo substr($item,2);
}
You could perform another explode on your initial array on the colon, seperate the number and the value, then feed them into a array using the number as the key, eg:
$itemsString = "1:asd, 1:wer, 2:dfg, 3:gfg, 3:sdfss"; //and so forth
$sorted_array = [];
$itemsArray = explode(", ", $itemsString);
foreach($itemsArray as $item) {
$subItemsArray = explode(":", $item);
$sorted_array[$subItemsArray[0]][] = $subItemsArray[1];
}
print_r($sorted_array);
Which would mean $sorted_array would be pre-sorted for you (or easily sortable with ksort()):
Array
(
[1] => Array
(
[0] => asd
[1] => wer
)
[2] => Array
(
[0] => dfg
)
[3] => Array
(
[0] => gfg
[1] => sdfss
)
)
you can display them like this
$itemsArray = explode(", ", $itemsString);
foreach($itemsArray as $item){
if(strpos($item, "1:") || strpos($item, "1:") ===0 ){
echo substr($item,2)
;}
}

PHP - Delete all duplicates in array

How can I delete duplicates from multiple arrays?
pinky and cocos are double in my array. All words which are double, must be removed. If those are removed, I will put these words in my select.
I get those words from my database.
The query:
$queryClient = " SELECT DISTINCT `clients` FROM `reps` WHERE `clients` != ''";
This is my code:
while($row = mysql_fetch_assoc($resultClient)){
$names = explode(",", $row['clients']);
echo '<pre>'; print_r($names); echo '</pre>';
}
Result: (Those food words are just an example)
Array
(
[0] => chocolate
)
Array
(
[0] => vanilla
[0] => cocos
)
Array
(
[0] => strawberry
)
Array
(
[0] => pinky
[1] => watermelon
[2] => melon
[3] => cocos
)
Array
(
[0] => pinky
)
Array
(
[0] => dark-chocolate
)
I tried this in my while loop but it did not work:
$array = array_unique($names, SORT_REGULAR);
How can I remove all duplicates? Can you help me or do you have a solution for my problem? Help.
Here's a one-liner:
print_r(array_unique(call_user_func_array('array_merge', $names)));
First merge all subarrays into one, then get unique values.
Full example:
$names = array();
while($row = mysql_fetch_assoc($resultClient)){
$names[] = explode(",", $row['clients']);
}
print_r(array_unique(call_user_func_array('array_merge', $names)));
You can just do a little trick:
Flatten, count and then remove all except the last.
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$flatArray = [];
foreach($it as $v) {
$flatArray[] = $v; //Flatten array
}
//Note you can do array_unique on the flat array if you also need to flatten the array
$counts = array_count_values($flatArray); //Count
foreach ($array as &$subarray) {
foreach ($subarray as $index => $element) {
$counts[$element]--;
if ($counts[$element] > 0) { //If there's more than 1 left remove it
unset($subarray[$index]);
}
}
}
This will remove duplicates nested exactly on the 2nd level without flattening the original array.
http://sandbox.onlinephpfunctions.com/code/346fd868bc89f484dac48d12575d678f3cb53626
first you need to join your array before you can filter out the duplicates:
<?php
$allNames = [];
while($row = mysql_fetch_assoc($resultClient)){
$names = explode(",", $row['food']);
$allNames[] = $names;
}
$allNames = array_merge(...$allNames); //Join everything to a one dimensional array
$allNames = array_unique($allNames); // Only keep unique elementes
print_r($allNames);

How to create an array from list in file

I have a text file countries.txt with a list of all countries:
1. Australia
2. Austria
3. Belgium
4. US
I want to create an array in country_handler.php like this:
$countries = array(
'1'=>'Australia',
'2'=>'Austria',
'3'=>'Belgium',
'4'=>'US'
);
How to do that?
Better you can use this in a function like below - then just called this function from any where
function getCountryList()
{
return array(
'1'=>'Australia',
'2'=>'Austria',
'3'=>'Belgium',
'4'=>'US'
);
}
$data = file_get_contents('countries.txt');
$countries = explode(PHP_EOL, $data);
$file = file('countries.txt');
$countries = array();
foreach ($file as $line) {
#list ($index, $country) = explode('.', $line);
$countries[trim($index)] = trim($country);
}
print_r($countries);
$lines = file('countries.txt');
$newArr = array();
foreach ($lines as $line) {
$erg = preg_split('/\.\s+/', $line);
$newArr[$erg[0]] = $erg[1];
}
var_dump($newArr);
Luckily (sometimes) regex doesn't include newlines in the ., so you can do this:
$contents = file_get_contents('countries.txt');
preg_match_all('#(\d+)\.\s+(.+)#', $contents, $matches);
print_r($matches);
The regex means:
(\d+) -- a number (save this)
\. -- a literal dot
\s+ -- white space
(.+) -- any character except \n or \r (end-of-line) (save this)
Which results in:
Array
(
[0] => Array
(
[0] => 1. Australia
[1] => 2. Austria
[2] => 3. Belgium
[3] => 4. US
)
[1] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
[2] => Array
(
[0] => Australia
[1] => Austria
[2] => Belgium
[3] => US
)
)
and I'm sure from [1] and [2] you can make the keyed array you need.
array_combine to the easy rescue:
$countries = array_combine($matches[1], $matches[2]);
Try this:
<?php
$data = file_get_contents('countries.txt');
$countries = explode(PHP_EOL,$data);
$cnt = 1;
foreach($countries as $val) {
if($val <>"") {
$res[$cnt] = strstr(trim($val), ' ');
$cnt++;
}
}
print_r($res);
?>

PHP: checking array to see if values match, display those values

I am generating an array from a while loop, and I would like to eventually use this array to display data.
while($row = $database->fetch(PDO::FETCH_ASSOC)
{
$value_1 = $row['value_1'];
$value_2 = $row['value_2'];
$data[] = array("value_1"=>$value_1,"value_2"=>$value_2);
}
so the $data[] would display using print_r I get something like this:
Array
(
[0] => Array
(
[value_1] => Hello World
[value_2] => venus
)
[1] => Array
(
[value_1] => Hello World
[value_2] => pluto
)
[2] => Array
(
[value_1] => Hello Moon
[value_2] => Halloween
)
)
My question is, how would I do a foreach loop or display such a way where if I wanted to get all data, but consolidate the same values?
Ex:
Hello World to venus pluto
Hello Moon to Halloween
I know those sentences doesn't make sense, but as you can see Hello World would be consolidated and I would need to add an " to" in between value_1 and value_2
Hope my question is understandable.
Thanks!
Try something like this. (Not Tested)
$match = array();
foreach($data as $d) {
if (isset($match[$d['value_1']])) {
$match[$d['value_1']] = $match[$d['value_1']].' '.$d['value_2'] ;
} else {
$match[$d['value_1']] = $d['value_1']. ' to '. $d['value_2'];
}
}
print_r($match);
I think for this first you need to create new array as follows:
$new_array = array();
//consider your original array is $data
foreach($data as $row){
if (array_key_exists($row['value_1'], $new_array)) {
$new_array[$row['value_1']] = $new_array[$row['value_1']]. " ".
$row['value_2'];
}
else {
$new_array[$row['value_1']] = $row['value_2'];
}
}
Then display it by iterating:
foreach($new_array as $key => $value){
echo $key ."to". $value;
}
foreach($data as $d) {
echo $d['value_1'], ' to ', $d['value_2']; // this is if you want to echo the content
// this code is to insert 'to' in the middle of value_1 and value_2
$value_2 = $d['value_2'];
unset($d['value_2']);
array_push($d, "to", $value_2);
unset($value_2);
}
Also you don't need to assign the $row value to another value:
$value_1 = $row['value_1']; // remove this
$value_2 = $row['value_2']; // remove this
$data[] = array("value_1" => $row['value_1'], "value_2" => $row['value_2']);

PHP: separate value in array according to alphabate order

i want to find values in array according to alphabate and want to make list in of array values according to alphabate order.
my array is like that:
Array (
[0] => Array
(
[0] => Adidas
[1] => AKG
[2] => Apple
[3] => Barrats
[4] => Canon
[5] => Dell
[6] => Dixons
[7] => HTC
[8] => Liverpool
[9] => Microsoft
[10] => Pirelli Tyres
[11] =>
)
)
and i want to make a list of values according to alphabate like this:
A
________
Adidas
AKG
plz any idea?
You're after asort
asort($a);
foreach($a AS $v) {
echo $v . "<br />";
}
Could use some optimization, but does exactly what you asked:
$a = array("Chicken","Fish","Hello","Lebowski","What","hey","foo");
asort($a);
$alphaArr = array();
foreach(range('A', 'Z') as $letter) {
// create empty array at offset for current letter
$alphaArr[$letter] = array();
foreach($a as $item) {
// if the first letter starts with current letter
// push it into subarray
if (substr(strtolower($item),0,1) == strtolower($letter)) {
$alphaArr[$letter][] = $item;
}
}
}
print_r($alphaArr);
Hardly comprehensible question, but I think you are looking for sort.
$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
reset($fruits);
while (list($key, $val) = each($fruits)) {
echo "fruits[".$key."] = ".$val."\n";
}
Your array is already sorted.
Get hold of the inner array and then loop over the values.
Whenever the first letter changes you know its the next letter.
If you want to resort the list by the first letter of the company name, here's one way:
$sorted = array();
foreach($companies as $company) {
$sorted[ strtoupper($company{0}) ][] = $company;
}
Just sort your array using sort() function and then print it out.
To have these letter captions just substr first letter and then compare to previou one:
$old='';
foreach ($words as $name) {
if ($name[0] != $old) {
echo $name[0]."<hr>\n";
}
echo $name."<br>\n";
$old=$name[0];
}

Categories