I'm trying to make an associative array from my string, but nothing works and I don't know where the problem is.
My string looks like:
$string = "somethink;452;otherthink;4554;somethinkelse;4514"
I would like to make an associative array, where "text" is the key, and the number is value.
Somethink => 452 otherthink => 4554 Somethinkelse => 4514
I tried to convert the string into an array and then to the associative array but it's not working. I decided to use:
$array=explode(";",$string);
Then tried to use a foreach loop but it's not working. Can somebody help?
Using regex and array_combine:
$string = "somethink;452;otherthink;4554;somethinkelse;4514";
preg_match_all("'([A-Za-z]+);(\d+)'", $string, $matches);
$assoc = array_combine($matches[1], $matches[2]);
print_r($assoc);
Using a traditional for loop:
$string = "somethink;452;otherthink;4554;somethinkelse;4514";
$arr = explode(";", $string);
for ($i = 0; $i < count($arr); $i += 2) {
$assoc[$arr[$i]] = $arr[$i+1];
}
print_r($assoc);
Result:
Array
(
[somethink] => 452
[otherthink] => 4554
[somethinkelse] => 4514
)
Note that there must be an even number of pairs; you can add a condition to test this and use a substitute value for any missing keys, or omit them.
Related
I got array like:
$array = array(
3A32,
4565,
7890,
0012,
A324,
9002,
3200,
345A,
0436
);
Then I need to find which elements has two numbers. The value of number can change.
If values were:
$n1 = 0;
$n2 = 3;
For that search preg_match() should return (3200,0436)
If values were:
$n1 = 0;
$n2 = 0;
preg_match() should return (0012,3200,9002)
Any idea?
Thanks.
I got your logic after looking multiple times on your input array as well as output based on given numbers.
Since i am not good in regular expression at all, i will go to find out answer with commonly know PHP functions.
1.Create a function which takes initial array as well as those search numbers in array form (so that you can search any number and any length of numbers).
2.Now iterate over initial array, split each value to convert to array and do array_count_value() for both split array and numbers array. now apply check and see exact match found or not?
3.Assign this match to a new array declared under the function itself.
4.Return this array at the end of function.
$n1 = 0;
$n2 = 0;
function checkValues($array,$numbers=array()){
$finalArray = [];
if(!empty($numbers)){
foreach($array as $arr){
$splitArr = str_split($arr);
$matched = true;
$count_number_Array = array_count_values($numbers);
$count_split_array = array_count_values($splitArr);
foreach($count_number_Array as $key=>$value){
if(!isset($count_split_array[$key]) || $count_split_array[$key] < $value){
$matched = false;
break;
}
}
if($matched === true){
$finalArray[] = $arr;
}
}
}
return $finalArray;
}
print_r(checkValues($array, array($n1,$n2)));
Output: https://3v4l.org/7uWfC And https://3v4l.org/Tuu5m And https://3v4l.org/fEKTO
Instead of using preg_match, you might use preg_grep and dynamically create a pattern that will match the 2 values in each order using an alternation.
^[A-Z0-9]*0[A-Z0-9]*3[A-Z0-9]*|[A-Z0-9]*3[A-Z0-9]*0[A-Z0-9]*$
The character class [A-Z0-9] matches either a char A-Z or a digit 0-9.
Regex demo | Php demo
If you want to use other characters, you could also take a look at preg_quote to handle regular expression characters.
function getElementWithTwoValues($n1, $n2) {
$pattern = "/^[A-Z0-9]*{$n1}[A-Z0-9]*{$n2}[A-Z0-9]*|[A-Z0-9]*{$n2}[A-Z0-9]*{$n1}[A-Z0-9]*$/";
$array = array(
"3A32",
"4565",
"7890",
"0012",
"A324",
"9002",
"3200",
"345A",
"0436"
);
return preg_grep($pattern, $array);
}
print_r(getElementWithTwoValues(0, 3));
print_r(getElementWithTwoValues(0, 0));
Output
Array
(
[6] => 3200
[8] => 0436
)
Array
(
[3] => 0012
[5] => 9002
[6] => 3200
)
I have been trying to match a string with the values in an array and output the array strings starting from the string with the highest character match count. for example:
$array = array(
'mike'=>'book21',
'ben'=>'buzz',
'jack'=>'airdrone',
'july'=>'march',
'fred'=>'blend45'
);
$string = 'blenmaio2';
As you can see, 'blend45', has the highest matched characters, with a total of 4 matched characters. I want to be able to output them starting from the first four highest match count, here is an example of the output i want:
blend45
book21
march
buzz
This is my first time trying to help someone, so hopefully this does the trick. I know you can probably simplify the code a little, but this is what I have.
<?php
$array = array(
'mike'=>'book21',
'ben'=>'buzz',
'jack'=>'airdrone',
'july'=>'march',
'fred'=>'blend45'
);
$string = 'blenmaio2';
$sort_array=array(); //Empty array
foreach ($array as $key => $value){
$num = similar_text($value,$string); //Using similar text to compar the strings.
$sort_array[$value] = $num; //Adding the compared number value and sring value to array.
}
arsort($sort_array, SORT_REGULAR);//Sorting the array by the larges number.
print_r ($sort_array);
//creating another foreach statement to get the output you wanted.
$count = 0;
foreach($sort_array as $key => $value){
$count++;
echo $count.". ".$key."\n";
};
?>
Results:
Array
(
[blend45] => 4
[book21] => 3
[airdrone] => 3
[march] => 2
[buzz] => 1
)
1. blend45
2. book21
3. airdrone
4. march
5. buzz
I think the levenshtein() function would be the most appropriate method to achieve your goal:
$array = array(
'mike'=>'book21',
'ben'=>'buzz',
'jack'=>'airdrone',
'july'=>'march',
'fred'=>'blend45'
);
$string = 'blenmaio2';
uasort($array, function($a, $b) use ($string) {
$aDistance = levenshtein($string, $a);
$bDistance = levenshtein($string, $b);
return ($aDistance < $bDistance) ? -1 : 1;
});
print_r($array);
// Output:
// Array
// (
// [fred] => blend45
// [july] => march
// [mike] => book21
// [ben] => buzz
// [jack] => airdrone
// )
http://php.net/levenshtein
Update Use uasort() instead of usort() to preserve the array keys.
I just noticed that my answer compares the similarity, but doesn't meet the highest character count match, so sorry for that :)
Here you are my answer. It is a bit different, because I'm using levenshtein function for finding nearest between two words.
I'm using uasort to reorder the array in way you liked.
Of course you can replace the algorithm for nearest by your function.
<?php
$array = array(
'mike'=>'book21',
'ben'=>'buzz',
'jack'=>'airdrone',
'july'=>'march',
'fred'=>'blend45'
);
$string = 'blenmaio2';
function cmp($a,$b){
global $string;
$aa=levenshtein($a, $string);
$bb=levenshtein($b, $string);
if($aa>$bb)
return 1;
elseif($bb>$aa)
return -1;
else return 0;
}
uasort($array,cmp);
?>
<pre><?= print_r($array); ?></pre>
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!
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);
I have two preg_match() calls and i want to merge the arrays instead of replacing the first array. my code so far:
$arr = Array();
$string1 = "Article: graphics card";
$string2 = "Price: 300 Euro";
$regex1 = "/Article[\:] (?P<article>.*)/";
$regex2 = "/Price[\:] (?P<price>[0-9]+) Euro/";
preg_match($regex1, $string1, $arr);
//output here:
$arr['article'] = "graphics card"
$arr['price'] = null
preg_match($regex2, $string2, $arr);
//output here:
$arr['article'] = null
$arr['price'] = "300"
How may I match so my output will be:
$arr['article'] = "graphics card"
$arr['price'] = "300"
?
You could use preg_replace_callback and handle the merging inside the callback function.
If it were me this is how I would do it, this would allow for easier extension at a later date, and would avoid using a callback function. It could also support searching one string easily by replacing $strs[$key] and the $strs array with a singular string var. It doesn't remove the numerical keys, but if you are only ever to go on accessing the associative keys from the array this will never cause a problem.
$strs = array();
$strs[] = "Article: graphics card";
$strs[] = "Price: 300 Euro";
$regs = array();
$regs[] = "/Article[\:] (?P<article>.*)/";
$regs[] = "/Price[\:] (?P<price>[0-9]+) Euro/";
$a = array();
foreach( $regs as $key => $reg ){
if ( preg_match($reg, $strs[$key], $b) ) {
$a += $b;
}
}
print_r($a);
/*
Array
(
[0] => Article: graphics card
[article] => graphics card
[1] => graphics card
[price] => 300
)
*/
You can use array_merge for this if you store your results in two different arrays.
But your output depicted above is not correct. You do not have $arr['price'] if you search with regex1 in your string but only $arr['article']. Same applies for the second preg_match.
That means if you store one result in $arr and one in $arr2 you can merge them into one array.
preg_match does not offer the functionality itself.
Use different array for second preg_match ,say $arr2
Traverse $arr2 as $key => $value .
Choose non null value out of $arr[$key] and $arr2[$key], and write that value to $arr[$key].
$arr will have required merged array.
This should work for your example:
array_merge( // selfexplanatory
array_filter( preg_match($regex1, $string1, $arr)?$arr:array() ), //removes null values
array_filter( preg_match($regex2, $string2, $arr)?$arr:array() )
);