I have a string that looks like:
KEY1,"Value"KEY2,"Value"Key3,"Value"
This string will always vary in the number of keys/values i need an associative array:
array (
'KEY1' => 'Value',
'KEY2' => 'Value',
'KEY3' => 'Value'
);
of the data contained in the string, a regular expression would be best I suppose?
Assuming your values don't contain a " in them you can do:
$str = 'KEY1,"Value1"KEY2,"Value2"Key3,"Value3"';
$pieces = preg_split('/(?<=[^,]")/',$str,-1,PREG_SPLIT_NO_EMPTY);
$result = array();
foreach($pieces as $piece) {
list($k,$v) = explode(",",trim$piece);
$result[$k] = trim($v,'"');
}
See it in action!
php> $str = 'KEY1,"Value"KEY2,"Value"Key3,"Value"';
php> $hash = array();
php> preg_match_all("/(.*?),\"(.*?)\"/", $str, $m);
php> foreach($m[1] as $index => $key) {
... $hash[$key] = $m[2][$index];
... }
php> var_dump($hash);
array(3) {
["KEY1"]=>
string(5) "Value"
["KEY2"]=>
string(5) "Value"
["Key3"]=>
string(5) "Value"
}
If the key changes between values then you'll need preg_split(). If the key is always the same then explode() should be more than adequate.
Related
I have an array:
$a = [
"g41" => 1,
"g44" => 2,
"g53" => 3
];
And another array is:
$list = [
40,
41,
44,
46,
53
];
How to combine these arrays by partial key matches to produce the following results?
$result = [
"41" => 1,
"44" => 2,
"53" => 3,
"40" => null,
"46" => null
];
Iterate $list array and check for the key in the other $a array:
$a = array("g41" => 1, "g44" => 2, "g53" => 3);
$list = array(40, 41, 44, 46, 53);
$result = [];
foreach ($list as $key) {
$result[$key] = $a["g$key"] ?? null;
}
var_dump($result);
Output:
array(5) {
[40]=> NULL
[41]=> int(1)
[44]=> int(2)
[46]=> NULL
[53]=> int(3)
}
since you want to the result sequence follow $a, you may need to unset $list, and push remaining lists to $result
sample code as below:
<?php
$a=["g41"=>1,"g44"=>2,"g53"=>3];
$list=[40,41,44,46,53];
$result =[];
foreach($a as $key => $value){
$new_key = substr($key,1); //remove first character, if only you first key always single char, else you may use your own method to extract key
if(in_array($new_key,$list)){
$result[$new_key] = $value;
unset($list[array_search($new_key, $list)]);//remove used key
}
}
//push remaining as null
foreach($list as $v){
$result[$v] = null;
}
print_r($result);
write your custom script
$result = [];
foreach($a as $key => $value) $result[trim($key, 'g')] = $value;
foreach($list as $key) if (!isset($result[strval($key)]) $result[strval($key)] = null;
Loop the $list array
Check if the list value (prepended with g) exists in the $a array. If so, push it with the desired numeric key into the result array; if not, push it into an alternative array with the desired numeric key and the default value of null.
When finished iterating, append the data from the alternative array to the result array.
This will properly filter your data, apply the expected default values and sort the output exactly as requested.
Code: (Demo)
foreach ($list as $v) {
if (isset($a["g$v"])) {
$result[$v] = $a["g$v"];
} else {
$extra[$v] = null;
}
}
var_export(
array_replace($result ?? [], $extra ?? [])
);
I am using ?? [] to fallback to an empty array in case either of the arrays are never declared (never receive any elements).
It looks like what you want to do first is transform the keys in array $a. Then use your $list of keys to populate null values where none are present in $a.
$aKeys = preg_replace('/\D/', '', array_keys($a));
$a = array_combine($aKeys, $a);
$defaultList = array_fill_keys($list, null);
$list = array_merge($defaultList, $a);
I'm New in php My Simply Question I have a String then i want get in number. for example a=1,b=2,c=3, etc... I trying so many times I have Getting only strlen string count or length. Please Check My Example
$a = "abc" ;
echo $a // output 123
An alternative solution using array_keys()
$charmap = array(
"a" => "1",
"b" => "2",
"c" => "3"
);
$string = "abc";
$string = str_replace(array_keys($charmap), $charmap, $string);
$string="abc";
$list=[
"a"=>1,
"b"=>2,
"c"=>3
];
$keys = array_keys($list);
$values = array_values($list);
$new_string = str_ireplace($keys, $values, $string);
Something like this?
$charmap = array(
"a" => "1",
"b" => "2",
"c" => "3"
);
$string = "abc";
foreach($charmap as $char => $number){
$string = str_replace($char, $number, $string);
}
echo($string);
I am trying to separate them all according to white space.
$string = "1 2 3 10 12";
According to this string, I want to separate like that.
$a = "1";
$b = "2";
$c = "3";
$d = "10";
$e = "12";
After that, I would like to check those strings are included as the key of an array. Here is my array,
$data = [
"1" => "Book",
"2" => "Paper",
"3" => "Pencil",
"10" => "Eraser",
"11" => "Ruler",
];
So, How can I separate an array and store the parts in each variable?
And How to check those variable are included in array as a key? Sorry for my English :D. Thanks.
Use the explode function to seperate the values and then check if the array key exists using array key exists.
$stringArray = explode(" ",$string);
foreach($stringArray as $stringPeice){
if(array_key_exists($stringPeice, $data)){
//do something
}
}
You can use explode to create an array of keys and then use array_diff to get an array of keys that are not in the $data:
$string = "1 2 3 10 12";
$keys = explode(' ', $string);
$data = [
"1" => "Book",
"2" => "Paper",
"3" => "Pencil",
"10" => "Eraser",
"11" => "Ruler",
];
$diff = array_diff($keys, array_keys($data));
Here is the demo.
If you want to get the entries from $data whose key exists in $string, you can use array_intersect_key(), and array_fill_keys() to create an array containing keys from the result of exploding $string:
$o = array_intersect_key($data, array_fill_keys(explode(" ", $string), ""));
Here's a demo
I have an array that looks like this:
a 12 34
b 12345
c 123456
So the array looks like
$array[0] = "a 12 34"
$array[1] = "b 12345"
$array[2] = "c 123456"
I am trying to create an associative array such that
[a] => 12 34
[b] => 12345
[c] => 123456
Can I possibly split the array into two, one for containing "a, b, c" and another for their contents and use the array_combine()? Or are there any other ways?
You can do that within a loop like the snippet below demonstrates. Quick-Test here:
$array = array("a 12 34", "b 12345", "c 123456");
$array2 = array();
foreach($array as $data){
preg_match("#([a-z])(\s)(.*)#i", $data, $matches);
list(, $key, $space, $value) = $matches;
$array2[$key] = $value;
}
var_dump($array2);
// YIELDS::
array(3) {
["a"]=> string(5) "12 34"
["b"]=> string(5) "12345"
["c"]=> string(6) "123456"
}
Or using a Blend of array_walk() and array_combine() which can be Quick-Tested Here.
<?php
$array = array("a 12 34", "b 12345", "c 123456");
$keys = array();
array_walk($array, function(&$data, $key) use (&$keys){
$keys[] = trim(preg_replace('#(\s.*)#i', '', $data));;
$data = trim(preg_replace('#(^[a-z])#i', '', $data));
});
$array = array_combine($keys, $array);
var_dump($array);;
// YIELDS::
array(3) {
["a"]=> string(5) "12 34"
["b"]=> string(5) "12345"
["c"]=> string(6) "123456"
}
You can do it without any difficulty :) A simple loop is possible to do it.
Create new array
Lopp on each row
Split each data (explode(' ', $row, 2), strstr, substr, ...) ?
Put data on your new array $array[$key] = $value;
You could use a combination of array_map, array_column and array_combine:
$array = array_map(function ($v) { return explode(' ', $v, 2); }, $array);
$array = array_combine(array_column($array, 0), array_column($array, 1));
$word = array("red","or","bl","green","gr");
$colors = array( "re"=>"red" ,
"or"=>"orange",
"bc"=>"black" ,
"br" =>"brown",
"gr" =>"green"
);
//find the values of array word in array colors doesn't matter if its key or value.
//output should display both key and value.
re => red
or => orange
gr => green
Here is a function to compute the intersection(?) of both the key and values to $array from an array $contains:
function array_full_intersect($array, $contains) {
$result = array();
// Go through each element in $contains.
foreach ($contains as $val) {
// If $val is a key in $array, add key-value pair to $result.
if (isset($array[$val])) {
$result[$val] = $array[$val];
} else {
// Otherwise, if $val is a value in $array, search for the value and get its key.
// Add key-value pair to $result.
$key = array_search($val, $array);
if ($key !== false) {
$result[$key] = $val;
}
}
}
return $result;
}
If you would prefer a more compact solution, use what is described in the comments:
function array_full_intersect($array, $contains) {
return array_merge(array_intersect_key($array, array_flip($contains)), array_intersect($array, $contains));
}
Use as:
$result = array_full_intersect($colors, $word);
Using PHP array functions:
$values = array_intersect($colors, $word);
$flip = array_flip($colors);
$flipValues = array_intersect($flip, $word);
$keys = array_flip($flipValues);
$result = array_merge($values, $keys);
Taking this apart:
$values = array_intersect($colors, $word);
creates an array with all of the members of $colors whose value is the same as a value in $word, i.e.
$values = array(
"re"=>"red",
"gr" =>"green"
);
2. $flip = array_flip($colors);
This flips the keys and values of $colors, so it is:
$flip = array( "red" => "re",
"orange" => "or",
"black" => "bc",
"brown" => "br",
"green" => "gr"
);
$flipValues = array_intersect($flip, $word);
This uses array_intersect again, but on the keys (which are the values in $flip). So this will be
$flip = array( "orange" => "or",
"green" => "gr"
);
4. $keys = array_flip($flipValues);
This flips the results back again:
$keys= array( "or" => "orange",
"gr" => "green"
);
Then array_merge combines $values and $keys eliminating duplicates.