Before I write my own function to do it, is there any built-in function, or simple one-liner to convert:
Array
(
[0] => pg_response_type=D
[1] => pg_response_code=U51
[2] => pg_response_description=MERCHANT STATUS
[3] => pg_trace_number=477DD76B-B608-4318-882A-67C051A636A6
)
Into:
Array
(
[pg_response_type] => D
[pg_response_code] =>U51
[pg_response_description] =>MERCHANT STATUS
[pg_trace_number] =>477DD76B-B608-4318-882A-67C051A636A6
)
Just trying to avoid reinventing the wheel. I can always loop through it and use explode.
I can always loop through it and use explode.
that's what you should do.
Edit - didn't read the question right at all, whoops..
A foreach through the array is the quickest way to do this, e.g.
foreach($arr as $key=>$val)
{
$new_vals = explode("=", $val);
$new_arr[$new_vals[0]] = $new_vals[1];
}
This should be around five lines of code. Been a while since I've done PHP but here's some pseudocode
foreach element in the array
explode result on the equals sign, set limit = 2
assign that key/value pair into a new array.
Of course, this breaks on keys that have more than one equals sign, so it's up to you whether you want to allow keys to have equals signs in them.
You could do it like this:
$foo = array(
'pg_response_type=D',
'pg_response_code=U51',
'pg_response_description=MERCHANT STATUS',
'pg_trace_number=477DD76B-B608-4318-882A-67C051A636A6',
);
parse_str(implode('&', $foo), $foo);
var_dump($foo);
Just be sure to encapsulate this code in a function whose name conveys the intent.
Related
How to add an element to an array using a key as ordinal element?
Before all, this is a theoretical question, and I'm looking for an answer instead of a way to reach the goal.
I've a function that generate a key, and I'was asking myself if there's a key to add to an array an element as ordinal element
$a=[];
$key=generateKey();
$a[$key]="pino";
var_export($a);
I was hoping this result:
array (
0 => 'pino'
)
A more advanced situation could be
array (
0 => 'a',
'7239ea2b5dc943f61f3c0a0276c20974' => 'b',
1 => 'c',
'c180aaadf5ab10fb3a733f43f3ffc4b3' => 'lino',
'48bb6e862e54f2a795ffc4e541caed4d' => 'gino',
2 => 'pino', // <- take 2 as index
)
EDIT
An hypothetic implementation of generateKey:
function generateKey($array){
$_rv=0;
foreach ($array as $k => $v){
if(is_numeric($k)==false){
continue;
}
$_rv=$k+1;
}
return $_rv;
}
I did not understand what was your real question... but as I have understood by your comment...
$a=[];
$key=generateKey();
to assign key to arry in php... below line is correct.
$a[$key]="pino";
If you want data in form of {key:value}...
var_export(json_encode($a));
If I understand correctly you just want to get highest numerical index of an array. You may try this:
$maxIdx = max(array_filter(array_keys($array), 'is_numeric')) ?: -1;
$array[$maxIdx + 1] = 'pino';
Looking the documentation of array-key-last I realized that the count function could achieve to generate a new numeric key without be cpu bounding:
$key=count($a);
$a[$key]="pino";
var_export($a);
I am working on a small CMS which takes a developer stdClass object and processes it accordingly. The stdClass contains arrays and other objects. One of these objects is a variables object. There maybe lots of variables objects.
I will just explain this instead of showing the code to make it less confusing. The developer specifies a variable and a set of values that may go into that variable. The values that the user specifies maybe multidimensional arrays. This is an example of how the variables object is created:
//Add variable1
$variable = $variables[] = new stdClass;
$variable->name = 'var1'; $variable->generator = 'function'; $variable->value = 'v'; $variable->enum = array (array('Mars', 9.8), array('Earth', 3.77)); $variable->description; $variable->callback = 'callback_function';
//Add variable2
$variable = $variables[] = new stdClass;
$variable->name = 'var1'; $variable->generator = 'function'; $variable->value = 'v'; $variable->enum = array (array('Mars', 9.8), array('Earth', 3.77)); $variable->description; $variable->callback = 'callback_function';
At some point in the stdClass the developer has to specify where the variables should be placed. The placeholder template looks like this: $variables[0] which selects the first variable or $variables[0][1] which selects the first variable and then the first element in that variable. I hope that makes sense.
I have to come up with a php algorithm that go through a piece of text and replace all the placeholders with the correct values.
My solution
Get all the variables->value into a new array. I have done this successfully.
Get all the placeholders in a piece of text. I am stuck at this point. I don't use regular expressions much.
I started by using:
preg_match_all('/\$variables[[0-9a-zA-Z]+]/', $text, $matched_placeholders);
..but this will only match $variables[0] and I am tring to expand this to match variations such as: $variables[0][1] or $variables[0][2][0], etc.
Once I have the placeholders into an array and the variables values into another array. I can do a foreach loop and replace all the placeholders.
Any advice will be appreciated. What regular expression pattern should I use to match this $variables[0][2][0]...
Your preg_match_all function will look something like:
preg_match_all('/\$variables((\[[0-9a-zA-Z]+\])*)/', $text, $matched_placeholders);
This will match:
$variables
$variables[#]
$variables[#][#]
and so on
And will store the [#][#][#]... portion in $matched_placeholders[1]
Test with $text = '$variables[0][1] or $variables[0][2][0]';:
Array (
[0] => Array (
[0] => $variables[0][1]
[1] => $variables[0][2][0]
)
[1] => Array (
[0] => [0][1]
[1] => [0][2][0]
) // The rest is just "noise"
[2] => Array ( [0] => [1] [1] => [0] )
)
If, for example, you wanted to rename your variable (since I have no idea what you're actually trying to do but just helping you with the regex part), you could do:
$text = preg_replace('/\$variables((\[[0-9a-zA-Z]+\])*)/', '\$newvar$1', $text);
which would replace all occurences of $variables with $newvar.
This will work :-
str.replaceAll( , );
Suppose I've got the following string:
) [6] => Array ( [2014-05-05 00:0] => My actual content
If I want to only be left with My actual content at the end, what is the best way to split the entire string?
Note: the words My actual content are and can change. I'm hoping to cut the string based on the second => string as this will be present at all times.
It seems you're just looking to find the first value of an array with keys you do not know. This is super simple:
Consider the following array:
$array = array(
'2014-05-22 13:36:00' => 'foo',
'raboof' => 'eh',
'qwerty' => 'value',
'8838277277272' => 'test'
);
Method #1:
Will reset the array pointer to the first element and return it.
Using reset:
var_dump( reset($array) ); //string(3) "foo"
DEMO
Method #2:
Will reset the entire array to use keys of 0, 1, 2, 3...etc. Useful if you need to get more than one value.
Using array_values:
$array = array_values($array);
var_dump( $array[0] ); //string(3) "foo"
DEMO
Method #2.5:
Will reset the entire array to use keys of 0, 1, 2, 3...etc and select the first one into the $content variable. Useful if you need to get more than one value into variables straight away.
Using list and array_values:
list( $content ) = array_values($array);
var_dump( $content ); //string(3) "foo"
DEMO
Method #3:
Arrays are iteratable, so you could iterate through it but break out immediately after the first value.
Using a foreach loop but break immediatly:
foreach ($array as $value) {
$content = $value;
break;
}
var_dump($content); //string(3) "foo"
DEMO
To Answer your question, on extracting from a string based on last 'needle'...
Okay, this is quite an arbitrary question, since it seems like you're showing us the results from a print_r(), and you could reference the array key to get the result.
However, you mentioned "... at the end", so I'm assuming My actual content is actually right at the end of your "String".
In which case there's a very simple solution. You could use: strrchr from the PHP manual - http://www.php.net/manual/en/function.strrchr.php.
So you're looking at this: strrchr($string, '=>');
Hope this answers your question. Advise otherwise if not please.
you have to use foreach loop in a foreach to get the multi dimentional array values.
foreach($value as $key){
foreach($key as $val){
echo $val;
}
}
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);
Having a brain freeze over a fairly trivial problem. If I start with an array like this:
$my_array = array(
'monkey' => array(...),
'giraffe' => array(...),
'lion' => array(...)
);
...and new elements might get added with different keys but always an array value. Now I can be sure the first element is always going to have the key 'monkey' but I can't be sure of any of the other keys.
When I've finished filling the array I want to move the known element 'monkey' to the end of the array without disturbing the order of the other elements. What is the most efficient way to do this?
Every way I can think of seems a bit clunky and I feel like I'm missing something obvious.
The only way I can think to do this is to remove it then add it:
$v = $my_array['monkey'];
unset($my_array['monkey']);
$my_array['monkey'] = $v;
array_shift is probably less efficient than unsetting the index, but it works:
$my_array = array('monkey' => 1, 'giraffe' => 2, 'lion' => 3);
$my_array['monkey'] = array_shift($my_array);
print_r($my_array);
Another alternative is with a callback and uksort:
uksort($my_array, create_function('$x,$y','return ($y === "monkey") ? -1 : 1;'));
You will want to use a proper lambda if you are using PHP5.3+ or just define the function as a global function regularly.
I really like #Gordon's answer for its elegance as a one liner, but it only works if the targeted key exists in the first element of the array. Here's another one-liner that will work for a key in any position:
$arr = ['monkey' => 1, 'giraffe' => 2, 'lion' => 3];
$arr += array_splice($arr, array_search('giraffe', array_keys($arr)), 1);
Demo
Beware, this fails with numeric keys because of the way that the array union operator (+=) works with numeric keys (Demo).
Also, this snippet assumes that the targeted key is guaranteed to exist in the array. If the targeted key does not exist, then the result will incorrectly move the first element to the end because array_search() will return false which will be coalesced to 0 by array_splice() (Demo).
You can implement some basic calculus and get a universal function for moving array element from one position to the other.
For PHP it looks like this:
function magicFunction ($targetArray, $indexFrom, $indexTo) {
$targetElement = $targetArray[$indexFrom];
$magicIncrement = ($indexTo - $indexFrom) / abs ($indexTo - $indexFrom);
for ($Element = $indexFrom; $Element != $indexTo; $Element += $magicIncrement){
$targetArray[$Element] = $targetArray[$Element + $magicIncrement];
}
$targetArray[$indexTo] = $targetElement;
}
Check out "moving array elements" at "gloommatter" for detailed explanation.
http://www.gloommatter.com/DDesign/programming/moving-any-array-elements-universal-function.html