I got an php array like this:
array(3) {
[0]=> string(12) "server[edit]"
[1]=> string(14) "server[create]"
[2]=> string(12) "user[delete]"
}
I want to convert this to different arrays - for example an array named server with "edit" and "create" in it - and another array "user" with "delete".
Whats the right pattern for that ?
Thanks for any help!
Rather than trying a regex against the whole array, try matching against each individual value. Take a look at this as an example
$array = array(
'server[edit]',
'server[create]',
'user[delete]',
'dsadsa'
);
$newArray = array();
foreach($array as $value)
{
preg_match("~^(\w+)\[(\w+)\]$~", $value, $matches);
if(count($matches))
{
$key = $matches[1];
if(!isset($newArray[$key]))
$newArray[$key] = array();
$newArray[$key][] = $matches[2];
}
}
var_dump($newArray);
Related
I have 2 arrays:
a1 = 1,2,3,4,5,6,7,8
a2 = 1,3,5,7
I want to be able to compare both arrays where they match, combine them without duplicates and then attach a prefix or letter to the matching values.
expected result:
a3 - match1,2,match3,4,match5,6,match7,8
I have looked at array_intersect(), but I'm not sure how I would use it in my example.
This could be one for https://adventofcode.com !
This is probably not the most efficient solution performance- or memory-wise, but it should do the trick.
$a1 = [1,2,3,4,5];
$a2 = [1,3,5];
$result = [];
foreach($a1 as $item) {
if (in_array($item, $a2)) {
$result[] = 'match' . $item;
} else {
$result[] = $item;
}
}
See it in action here: https://3v4l.org/PlTIZ
Alternatively, You can use array_map() to achieve this with better performance and maintainable code.
Live demo.
$arr_one = [1,2,3,4,5];
$arr_two = [1,3,5];
$new_arr = array_map(function($arg) use ($arr_two) {
return in_array($arg, $arr_two) ? "prefix_{$arg}" : $arg;
}, $arr_one);
Output:
array(5) {
[0]=>
string(8) "prefix_1"
[1]=>
int(2)
[2]=>
string(8) "prefix_3"
[3]=>
int(4)
[4]=>
string(8) "prefix_5"
}
References
array_* → pre-built methods.
ternary operator → ? :
I've a string of key value pairs with a comma as a delimiter.
I need to go through the string get the key and value and push them into an array.
I'm having an issue with writing a Regex as the value is a decimal number.
An example of the string is as follows:
value,0.23,word,0.42,dog,0.28000000000000014,cat,0,car,17.369999999999997
Any idea how to write a correct regex?
Regex just gives me a headache!
You could try the below regex to get the key, value pairs.
([a-z]+),(\d+(?:\.\d+)?)
DEMO
You can use array_chunk():
$values = array_chunk(explode(',', $string), 2)
foreach ($values as $pair) {
list($key, $value) = $pair;
// do something
}
You can use the following code:
$str = 'value,0.23,word,0.42,dog,0.28000000000000014,cat,0,car,17.369999999999997';
$parts = explode(',', $str);
$result = array();
for($i=0; $i < count($parts); $i+=2) {
$result[$parts[$i]] = $parts[$i+1];
}
var_dump($result);
Output:
array(5) {
["value"]=>
string(4) "0.23"
["word"]=>
string(4) "0.42"
["dog"]=>
string(19) "0.28000000000000014"
["cat"]=>
string(1) "0"
["car"]=>
string(18) "17.369999999999997"
}
This question already has answers here:
Implode a column of values from a two dimensional array [duplicate]
(3 answers)
Closed 7 months ago.
My array is like: (Below is the dump extract)
array(3) {
[0]=> array(2) {
[0]=> string(4) "0013"
[1]=> float(28.936563322435)
}
[1]=> array(2) {
[0]=> string(4) "0003"
[1]=> float(35.514521271921)
}
[2]=> array(2) {
[0]=> string(4) "0007"
[1]=> float(47.577230340278)
}
I would like to extract its 1st value like 0013 or 0007 etc into a variable say $order such that the final result is something like this
$order= "0013,0003,0007";
I tried to do something like this:
foreach($array as $x){
$order = x[0].",";
}
BUT it only extracts the first element
You can do it using array_map() and implode():
$order = implode(',', array_map(function($a) { return $a[0]; }, $array));
// string '0013,0003,0007' (length=14)
Or, if you're using PHP 5.5 or above:
$order = implode(',', array_column($array, 0));
To achieve what you desire you can use
$order = implode(',', array_column($array, 0));
for($i=0; $i<count($array); $i++){
$res[$i]=$array[$i][0];
}
$order=implode(",", $res);
This will give you a string with the first values of your nested arrays, all comma-separated.
$arr = array();
foreach($a as $k=>$v){
$arr[] = $v[0];
}
$order = implode(',', $arr);
I have a string like as below.
$string = "height=175cm weight=70kgs age=25yrs"
String contents are key value pairs each pair are separated by a Tab. I want each key value pairs as separate variable and prints out each.
I have tried with below code but i am not getting proper result please help me where i went wrong.
$string = "height=175cm weight=70kgs age=25yrs";
$pattern = "(([^=]*)\s*=\s*(.*))";
if (preg_match($pattern,$string,$match)) {
echo "<pre>";
print_r($match);
} else {
echo "not matche\n";
}
Result:
Array
(
[0] => height=175cm weight=70kgs age=25yrs
[1] => height
[2] => 175cm weight=70kgs age=25yrs
)
You can use this code:
$string = "height=175cm weight=70kgs age=25yrs";
if (preg_match_all('/\s*([^=]+)=(\S+)\s*/', $string, $matches)) {
$output = array_combine ( $matches[1], $matches[2] );
print_r($output);
}
OUTPUT:
Array
(
[height] => 175cm
[weight] => 70kgs
[age] => 25yrs
)
You can use this:
$string = "height=175cm weight=70kgs age=25yrs";
$pattern = "/(\w+)=(\d+)(\w+)/i";
if(preg_match_all($pattern,$string,$match))
{
var_dump($match);
}
Result:
array(4) {
[0]=>
array(3) {
[0]=>
string(12) "height=175cm"
[1]=>
string(12) "weight=70kgs"
[2]=>
string(9) "age=25yrs"
}
[1]=>
array(3) {
[0]=>
string(6) "height"
[1]=>
string(6) "weight"
[2]=>
string(3) "age"
}
[2]=>
array(3) {
[0]=>
string(3) "175"
[1]=>
string(2) "70"
[2]=>
string(2) "25"
}
[3]=>
array(3) {
[0]=>
string(2) "cm"
[1]=>
string(3) "kgs"
[2]=>
string(3) "yrs"
}
}
I've pasted a code sample below which helps you to solve your problem. Certainly, it is not very tightly compressed and has quite a few more lines of code than the other answers (which are all good answers!).
The reason I did this was because it looks like you may benefit from an explanation that takes you one step at a time in the progression of solving your problem, so that you can understand what is happening along the way.
Here's the code you can use:
<?php
$string = "height=175cm\tweight=70kgs\tage=25yrs";
// Divide your string into an array, with each element
// in the array being a string with a key-value pair
$pairs = explode("\t", $string);
// See what the array of pair strings looks like.
// print_r($pairs);
// Create an array to get it ready to hold key-value pairs.
$results = array();
// For each string in your array, split at the equal sign
// and set values in the $results array.
foreach ($pairs as $pair) {
$exploded_pair = explode("=", $pair);
// See what each exploded pair array looks like.
// print_r($exploded_pair);
$key = $exploded_pair[0];
$value = $exploded_pair[1];
$results[$key] = $value;
}
print_r($results);
Instead of using regular expressions, this makes use of the explode function in PHP. You can read the documentation on explode found here.
You said that your input string is separated by tabs, which is why the assignment statement for $string has \t instead of spaces. If you were to use spaces instead of tabs, then make sure that you change
$pairs = explode("\t", $string);
to
$pairs = explode(" ", $string);
I have 2 json data from nosql. first match if the search word match in $array1, get the item number then put item number into $array2, get the price of custom search require. But my code cause Invalid argument supplied for foreach() in
foreach($json2[$num] as $data2)
$str = 'paper';
$array1 = '[{"a":"1","b":"book"},{"a":"2","b":"paper"}]';
$array2 = '[{"1":["17.00","22.00"]},{"2",["4.50","6.00"]}]';
$json1 = json_decode($array1);
$json2 = json_decode($array2,true);
foreach($json1 as $data1){
if(preg_match('#'.$data1->b.'#',$str,$match)){
$num = $data1->a; // $num = 2
}
}
foreach($json2[$num] as $data2){
foreach($data2 as $newdata){
echo $newdata.'<br />'; // 4.50, 6.00
}
}
First off your JSON for $array2 is not valid. It should be:
[{"1":["17.00","22.00"]},{"2":["4.50","6.00"]}]
-----------------------------^
This should be a ":", not a ","
Your JSON is actually an array of objects (arrays). var_dump($json2); shows this.
array(2) {
[0]=>
array(1) {
[1]=>
array(2) {
[0]=>
string(5) "17.00"
[1]=>
string(5) "22.00"
}
}
[1]=>
array(1) {
[2]=>
array(2) {
[0]=>
string(4) "4.50"
[1]=>
string(4) "6.00"
}
}
}
You're gonna need to loop over it like this:
foreach($json2 as $data2){
if(array_key_exists($num, $data2)){
$data2 = $data2[$num];
foreach($data2 as $newdata){
echo $newdata.'<br />'; // 4.50, 6.00
}
}
}
If $num = 2 in your comments is correct, you'll be accessing the third element in $json2 but you can't since there only are two.
Update
Oops, how did I miss this? Your $array2 already has the indices right there, you're just not loading them properly. You can simply loop through $array2 and look for the key. However, a better solution would be to load the data properly, by filling $array2 as a dictionary rather than a list.