I have a variable that contains text with values according to an example below:
$data = "5:7|4:1|504:2|1:3|"
And I would like to achieve results like this:
$data[5] = 7;
$data[4] = 1;
$data[504] = 2;
$data[1] = 3;
I tried with explode:
$data = explode("|", $data);
//but it makes $data[0]="5:7"; $data[1]="4:1"; and so on.
Should I use explode again? Is it has any sense, or is there another way? I would like to ask for a hint or help.
There may be a more clever way, but I'd do it like this:
$data = array();
foreach (explode("|", $your_data) as $part)
{
$pieces = explode(':', $part);
// Assumes we have 2 pieces, might want to make sure here...
$data[$pieces[0]] = $pieces[1];
}
Also, I'm not sure what this data represents but keep in mind that array keys will overwrite each other, so 1:1|1:2 will result in an array with only one item (the last piece). There may be good reason to take another approach.
Sure, explode again:
$data = "5:7|4:1|504:2|1:3";
$array = array();
foreach (explode('|', $data) as $pair) {
list($id, $val) = explode(':', $pair);
$array[$id] = $val;
}
Yes you should use explode twice, like this
$newData = array();
$pairs = explode('|',$data);
foreach($pairs as $pair){
$tmp = explode(':',$pair);
$newData[$tmp[0]] = $tmp[1];
}
Try using a regexp:
$data = preg_split ("\||:", $data);
One line version:
$data = array_map(function($d) { return (int)explode(":", $d)[1]; }, explode("|", $data));
Related
Trying to use the implode() function to add a string at the end of each element.
$array = array('9898549130', '9898549131', '9898549132');
$attUsers = implode("#txt.att.net,", $array);
print($attUsers);
Prints this:
9898549130#txt.att.net,9898549131#txt.att.net,9898549132
How do I get implode() to also append the glue for the last element?
Expected output:
9898549130#txt.att.net,9898549131#txt.att.net,9898549132#txt.att.net
//^^^^^^^^^^^^ See here
There is a simpler, better, more efficient way to achieve this using array_map and a lambda function:
$numbers = ['9898549130', '9898549131', '9898549132'];
$attUsers = implode(
',',
array_map(
function($number) {
return($number . '#txt.att.net');
},
$numbers
)
);
print_r($attUsers);
This seems to work, not sure its the best way to do it:
$array = array('9898549130', '9898549131', '9898549132');
$attUsers = implode("#txt.att.net,", $array) . "#txt.att.net";
print($attUsers);
Append an empty string to your array before imploding.
But then we have another problem, a trailing comma at the end.
So, remove it.
Input:
$array = array('9898549130', '9898549131', '9898549132', '');
$attUsers = implode("#txt.att.net,", $array);
$attUsers = rtrim($attUsers, ",")
Output:
9898549130#txt.att.net,9898549131#txt.att.net,9898549132#txt.att.net
This was an answer from my friend that seemed to provide the simplest solution using a foreach.
$array = array ('1112223333', '4445556666', '7778889999');
// Loop over array and add "#att.com" to the end of the phone numbers
foreach ($array as $index => &$phone_number) {
$array[$index] = $phone_number . '#att.com';
}
// join array with a comma
$attusers = implode(',',$array);
print($attusers);
$result = '';
foreach($array as $a) {
$result = $result . $a . '#txt.att.net,';
}
$result = trim($result,',');
There is a simple solution to achieve this :
$i = 1;
$c = count($array);
foreach ($array as $key => $val) {
if ($i++ == $c) {
$array[$key] .= '#txt.att.net';
}
}
I have a variable, let's call it $var that echoes out something like:
32-Widgets: 18,28-Widgets: 24,57-Widgets: 45,44-Widgets: 24,55-Widgets: 45
The variable is created from a combination of a form submission and jQuery Sortables (which is why everything ends up in one variable, not two). The order is very important.
What I'd like to end up with is two variables (can be arrays) that would be:
$newVar1 = 32,18,24,45,24
$newVar2 = Widgets: 18,Widgets: 24,Widgets: 45,Widgets: 24,Widgets: 45
I started by:
$newVars = explode(",",$var);
But I'm at a loss of where to go from there. I've tried a variety of statements such as:
foreach ($newVars as $newVar) :
//Various explode() functions tried here.
endforeach;
If anybody has any idea what I'm missing I would certainly appreciate the help.
Thank you,
Eric
It's not very pretty, but it'll do the trick.
<?php
$str = "32-Widgets: 18,28-Widgets: 24,57-Widgets: 45,44-Widgets: 24,55-Widgets: 45";
$entries = explode(",", $str);
$parts1 = array();
$parts2 = array();
foreach ($entries as $e)
{
$temp = explode("-", $e);
$parts1[] = $temp[0];
$parts2[] = $temp[1];
}
print_r($parts1);
print_r($parts2);
?>
Running example: http://ideone.com/KkL06f
Have you tried something like this:
public function just_a_test() {
$var = "32-Widgets: 18,28-Widgets: 24,57-Widgets: 45,44-Widgets: 24,55-Widgets: 45";
$vars = explode(',', $var);
$partsA = $partsB = array();
foreach ($vars as $aVar) {
preg_match('/^(\d+)-(Widgets: \d+)$/i', $aVar, $parts);
$partsA []= $parts[0];
$partsB []= $parts[1];
}
echo '<pre>';
print_r($partsA);
print_r($partsB);
echo '</pre>';
}
You could easily end up with output like yours by calling the implode() with each array.
I have a string that contains elements from array.
$str = '[some][string]';
$array = array();
How can I get the value of $array['some']['string'] using $str?
This will work for any number of keys:
$keys = explode('][', substr($str, 1, -1));
$value = $array;
foreach($keys as $key)
$value = $value[$key];
echo $value
You can do so by using eval, don't know if your comfortable with it:
$array['some']['string'] = 'test';
$str = '[some][string]';
$code = sprintf('return $array%s;', str_replace(array('[',']'), array('[\'', '\']'), $str));
$value = eval($code);
echo $value; # test
However eval is not always the right tool because well, it shows most often that you have a design flaw when you need to use it.
Another example if you need to write access to the array item, you can do the following:
$array['some']['string'] = 'test';
$str = '[some][string]';
$path = explode('][', substr($str, 1, -1));
$value = &$array;
foreach($path as $segment)
{
$value = &$value[$segment];
}
echo $value;
$value = 'changed';
print_r($array);
This is actually the same principle as in Eric's answer but referencing the variable.
// trim the start and end brackets
$str = trim($str, '[]');
// explode the keys into an array
$keys = explode('][', $str);
// reference the array using the stored keys
$value = $array[$keys[0][$keys[1]];
I think regexp should do the trick better:
$array['some']['string'] = 'test';
$str = '[some][string]';
if (preg_match('/\[(?<key1>\w+)\]\[(?<key2>\w+)\]/', $str, $keys))
{
if (isset($array[$keys['key1']][$keys['key2']]))
echo $array[$keys['key1']][$keys['key2']]; // do what you need
}
But I would think twice before dealing with arrays your way :D
My string is like the following format:
$string =
"name=xxx&id=11&name=yyy&id=12&name=zzz&id=13&name=aaa&id=10";
I want to split the string like the following:
$str[0] = "name=xxx&id=11";
$str[1] = "name=yyy&id=12";
$str[2] = "name=zzz&id=13";
$str[3] = "name=aaa&id=10";
how can I do this in PHP ?
Try this:
$matches = array();
preg_match_all("/(name=[a-zA-Z0-9%_-]+&id=[0-9]+)/",$string,$matches);
$matches is now an array with the strings you wanted.
Update
function get_keys_and_values($string /* i.e. name=yyy&id=10 */) {
$return = array();
$key_values = split("&",$string);
foreach ($key_values as $key_value) {
$kv_split = split("=",$key_value);
$return[$kv_split[0]] = urldecode($kv_split[1]);
}
return $return;
}
$string = "name=xxx&id=11&name=yyy&id=12&name=zzz&id=13&name=aaa&id=10";
$arr = split("name=", $string);
$strings = aray();
for($i = 1; $i < count($arr), $i++){
$strings[$i-1] = "name=".substr($arr[$i],0,-1);
}
The results will be in $strings
I will suggest using much simpler term
Here is an example
$string = "name=xxx&id=11;name=yyy&id=12;name=zzz&id=13;name=aaa&id=10";
$arr = explode(";",$string); //here is your array
If you want to do what you asked, nothing more or less , that's explode('&', $string).
If you have botched up your example and you have a HTTP query string then you want to look at parse_str().
I am trying to create a multi-dimensional array whose parts are determined by a string. I'm using . as the delimiter, and each part (except for the last) should be an array
ex:
config.debug.router.strictMode = true
I want the same results as if I were to type:
$arr = array('config' => array('debug' => array('router' => array('strictMode' => true))));
This problem's really got me going in circles, any help is appreciated. Thanks!
Let’s assume we already have the key and value in $key and $val, then you could do this:
$key = 'config.debug.router.strictMode';
$val = true;
$path = explode('.', $key);
Builing the array from left to right:
$arr = array();
$tmp = &$arr;
foreach ($path as $segment) {
$tmp[$segment] = array();
$tmp = &$tmp[$segment];
}
$tmp = $val;
And from right to left:
$arr = array();
$tmp = $val;
while ($segment = array_pop($path)) {
$tmp = array($segment => $tmp);
}
$arr = $tmp;
I say split everything up, start with the value, and work backwards from there, each time through, wrapping what you have inside another array. Like so:
$s = 'config.debug.router.strictMode = true';
list($parts, $value) = explode(' = ', $s);
$parts = explode('.', $parts);
while($parts) {
$value = array(array_pop($parts) => $value);
}
print_r($parts);
Definitely rewrite it so it has error checking.
Gumbo's answer looks good.
However, it looks like you want to parse a typical .ini file.
Consider using library code instead of rolling your own.
For instance, Zend_Config handles this kind of thing nicely.
I really like JasonWolf answer to this.
As to the possible errors: yes, but he supplied a great idea, now it is up to the reader to make it bullet proof.
My need was a bit more basic: from a delimited list, create a MD array. I slightly modified his code to give me just that. This version will give you an array with or without a define string or even a string without the delimiter.
I hope someone can make this even better.
$parts = "config.debug.router.strictMode";
$parts = explode(".", $parts);
$value = null;
while($parts) {
$value = array(array_pop($parts) => $value);
}
print_r($value);
// The attribute to the right of the equals sign
$rightOfEquals = true;
$leftOfEquals = "config.debug.router.strictMode";
// Array of identifiers
$identifiers = explode(".", $leftOfEquals);
// How many 'identifiers' we have
$numIdentifiers = count($identifiers);
// Iterate through each identifier backwards
// We do this backwards because we want the "innermost" array element
// to be defined first.
for ($i = ($numIdentifiers - 1); $i >=0; $i--)
{
// If we are looking at the "last" identifier, then we know what its
// value is. It is the thing directly to the right of the equals sign.
if ($i == ($numIdentifiers - 1))
{
$a = array($identifiers[$i] => $rightOfEquals);
}
// Otherwise, we recursively append our new attribute to the beginning of the array.
else
{
$a = array($identifiers[$i] => $a);
}
}
print_r($a);