I am getting from url value something like below:
$param = "{year:2019,month:5,id:3}"
I am not being able to convert it to array.
Can anybody please help me
Any time you have a string like this it is possible that values can cause problems due to containing values you don't expect (like commas or colons). So to just add to the confusion and because it was just an interesting experiment I came up with the idea of translating the string to a URL encoded string (with & and =) and then parsing it as though it was a parameter string...
parse_str(strtr($param, ["{" => "", "}" => "", ":" => "=", "," => "&"]), $params);
gives the $params array as...
Array
(
[year] => 2019
[month] => 5
[id] => 3
)
I think that needs to be parsed manually.
First explode on comma without {} to separate each of the key value pairs then loop and explode again to separate key from values.
$param = explode(",", substr($param, 1, -1));
foreach($param as $v){
$temp = explode(":", $v);
$res[$temp[0]] = $temp[1];
}
var_dump($res);
/*
array(3) {
["year"]=>
string(4) "2019"
["month"]=>
string(1) "5"
["id"]=>
string(1) "3"
}*/
https://3v4l.org/naIJE
Your json isn't well formatted. Try this:
$param = '{"year":2019,"month":5,"id":3}';
var_dump(json_decode($param, true));
Related
I'm studying php and I'm trying to figure out how to get the string "Juve_Milan" from this var_dump($_POST) :
array(5) {
["Juve_Milan"] => array(2) {
[0] => string(1)
"5" [1] => string(1)
"1"
}["Inter_Roma"] => array(2) {
[0] => string(1)
"4" [1] => string(1)
"4"
}["Napoli_Lazio"] => array(2) {
[0] => string(1)
"2" [1] => string(1)
"5"
}["name"] => string(0)
"" ["submit"] => string(5)
"Invia"
}
I could get all of them with:
foreach ($_POST as $param_name => $param_val) {
echo "<tr><td>".$param_name."</td><td>".$param_val[0]."-".$param_val[1]."</td></tr>";
}
But i want to get them exactly one by one, for example, if i want to get the string "Juve_Milan" or "inter_Roma" how can i do?
Without looping, how can i get the string value: "Juve_milan" or "Inter_Roma"? Becouse with the loop i can access them this way : $_POST as $param_name => $param_val
But i want to get them without loop, my first attempt was something like $_POST[0][0] but its wrong...
There are numbers of php array functions you can use.
You can use
array shift
to remove an element from an array and display it .e.g
$club = ['juve_millan', 'inter_roma', 'napoli_lazio'];
$juve = array_shift($club);
echo $juve;// 'juve_millan'
but note that the array is shortened by one element i.e. 'juve_millan' is no more in the array and also note that using
array_shift
over larger array is fairly slow
Array Slice function
PHP
array_slice()
function is used to extract a slice of an array e.g
$club = ['juve_millan', 'inter_roma', 'napoli_lazio'];
if I want to display
inter_roma
or assigned it to a variable, then I can do this
$roma = array_slice($club, 1, 1);// The first parameter is the array to slice, the second parameter is where to begin(which is one since most programming language array index start from 0 meaning juve_millan is zero, while inter_roma is 1, napoli_lazio is 2) and the length is 1 since i want to return a single element.
I hope you understand
You could iterate over keys of the main array like this:
foreach($_POST as $param_name => $param_val) {
echo "<tr><td>".$param_name."</td></tr>";
}
This will return each Juve_Milan, Inter_Roma etc. one by one. Although it's part of the code you already have, I believe this will return values you want only.
I have two arrays, or so I thought. One passes a Javascript object to php via a POST, the other gets data from a JS API which returns another object. I want to join both of these arrays. Here's the sample data and how it is obtained.
Name array which I get from API:-
array(5) { [0]=> string(1) "D" [1]=> string(1) "a" [2]=> string(1) "v" [3]=> string(1) "i" [4]=> string(1) "d" }
User array which is POST'd to my php script:-
array (
'userID' => '12345',
'time' => 'Monday 26th June 2017 22:12:37 AM',
)
Now I use the following to (try) and get both of these pieces of data into the same array to log to a file.
$nameoriginal = file_get_contents("/api");
$namejson = json_decode($name);
$user = var_export($_POST, true);
$detailstolog = $namejson + $user;
file_put_contents('/logs/names.log', $detailstolog);
However, I get a php error which states the first argument is not a valid array (i.e. $name is not valid). Why is this? What can I do to 'make' it an array?
I think the name 'array' is actually a string, hence the error. How do I make this an array, and is $array1 + $array2 the best way to do this?
I am trying to create something like:-
array (
'name' => 'david',
'userID' => '12345',
'time' => 'Monday 26th June 2017 22:12:37 AM',
)
Thanks for any help you can provide!
Copy the $_POST array to a new variable, then add the name to it.
$detailstolog = $_POST;
$name = implode('', $namejson);
$detailstolog['name'] = $name;
Sorry, but I don't understand where is JSON involved here, you're dealing with arrays, hence no need to decode anything from JSON.
The first array seems to be the word "David" split into chars. Then you just need to implode it and add it to your detailstolog array as the first element:
$detailstolog['name'] = implode("", $nameoriginal); // David
$detailstolog += $_POST;
I have a relatively large array of elements which I want to search for a string and replace any matches. I'm currently trying to do this using preg_replace and regular expressions:
preg_replace("/\d?\dIPT\.\w/", "IPT", $array);
I want to get all values which match either 00IPT.A or 0IPT.A (with 0 representing any numerical character and A representing any letter) and replace them with IPT. However, I'm getting array to string conversion notices. Is there any way to get preg_replace to accept an array data source? If not, is there any other way I could achieve this?
The documentation says that preg_replace should be able to accept array sources — this is the reason I'm asking.
The string or an array with strings to search and replace.
If subject is an array, then the search and replace is performed on every entry of subject, and the return value is an array as well.
The array is multidimensional if that helps (has multiple arrays under one main array).
preg_replace doesn't modify in place. To permanently modify $array, you simply need to assign the result of preg_replace to it:
$array = preg_replace("/\d{1,2}IPT\.\w/", "IPT", $array);
works for me.
$array = array('00IPT.A', '0IPT.A');
$array = preg_replace("/\d{1,2}IPT\.\w/", "IPT", $array);
var_dump($array);
// output: array(2) { [0]=> string(3) "IPT" [1]=> string(3) "IPT" }
Note: the \d{1,2} means one or two digits.
If you want to do this to a two-dimensional array, you need to loop through the first dimension:
$array = array( array('00IPT.A', 'notmatch'), array('neither', '0IPT.A') );
foreach ($array as &$row) {
$row = preg_replace("/\d{1,2}IPT\.\w/", "IPT", $row);
}
var_dump($array);
output:
array(2) {
[0]=> array(2) {
[0]=> string(3) "IPT"
[1]=> string(8) "notmatch"
}
[1]=> &array(2) {
[0]=> string(7) "neither"
[1]=> string(3) "IPT"
}
}
Note that you have to loop through each row by reference (&$row) otherwise the original array will not be modified.
Your value does not sit in the array as a simple element but as a subset right? Like so?
array (
array ('id' => 45, 'name' => 'peter', 'whatyouarelookingfor' => '5F'),
array ('id' => 87, 'name' => 'susan', 'whatyouarelookingfor' => '8C'),
array ('id' => 92, 'name' => 'frank', 'whatyouarelookingfor' => '9R')
)
if so:
<?php
foreach ($array as $key => $value) {
$array[$key]['whatyouarelookingfor'] =
preg_replace("/\d?\dIPT\.\w/", "IPT", $value['whatyouarelookingfor']);
}
Or if more elements have this, just go broader:
<?php
foreach ($array as $key => $value) {
$array[$key] =
preg_replace("/\d?\dIPT\.\w/", "IPT", $value);
}
your $array contains some further arrays. preg_replace works fine with arrays of strings, but not with arrays of arrays [of arrays...] of strings.
I am new to PHP and arrays and am wanting to understand the following array. I would also like to learn how I would go about assigning values to two particular array elements in PHP, i.e.:
["_gravity_form_lead"]=> array(5) { [1]=> string(4) "1000" [3]=> string(6) "strips" [2]=> string(2) "rp" [5]=> string(0) "" [6]=> string(0) "" }
1) What is the correct notation to define this array?
2) For the two array elements that are "", i.e.
[5]=> string(0) "" [6]=> string(0) ""
In PHP, how would I go about assigning values to these two array elements, that are NULL?
Hope this makes you understand ,
$array_before = array('_gravity_form_lead' => array( '1000', "strips", "rp", '', ''));
echo '<pre>';
echo 'This what it looks after print_r'.'<br>';
print_r($array_before);
echo '</pre>';
I don't see anything different and special than its said in the documentation
http://php.net/manual/en/language.types.array.php
Anyway, the concrete situation is.
$_gravity_form_lead = array(1=>1000, 3=>'strips', 2=>'rp', 5=>'', 6=>'');
As said in the documentation
Creating/modifying with square bracket syntax ¶
An existing array can be modified by explicitly setting values in it.
This is done by assigning values to the array, specifying the key in brackets. The key can also be omitted, resulting in an empty pair of brackets ([]).
$arr[key] = value;
You do modify the ones you need with [ ]
In this particular case:
$_gravity_form_lead[5] = 'something';
$_gravity_form_lead[6] = 'something else';
In order you want to modify all empty strings, you can iterate through the array and modify. You have two options while iterating - using reference &, which will modify the existent one, or creating new array.
foreach ($_gravity_form_lead as &$val) {
if ($val == '') {
$val = 'something';
}
}
The output after doing this is
var_dump($_gravity_form_lead);
/*
* array (size=5)
1 => int 1000
3 => string 'strips' (length=6)
2 => string 'rp' (length=2)
5 => string 'something' (length=9)
6 => &string 'something' (length=9)
*/
It would be defined somewhat like,
$arrayName = array('_gravity_form_lead' => array( 1=>'1000', 3=>"strips", 2=>"rp", 5=>'', 6=>''));
/* assign null instead of '' */
$arrayName['_gravity_form_lead'][5] = NULL;
$arrayName['_gravity_form_lead'][6] = NULL;
This question already has answers here:
Remove all elements from array that do not start with a certain string
(10 answers)
Closed 9 years ago.
I have a large SQL query which returns aggregate data.
My returned array is something like this:
array(37) { // I get 37 arrays returned
[0] => array(10) {
["groupId"] => string(1) "3" // the first param is just an id
["sessionCount84"] => string(1) "0"
["sessionCount1"] => string(1) "1"
} ...
Each sub-array will contains multiple keys with the word 'sessionCount' and a number following that and there could be many of them.
Is there a way to get all the values for keys which contain the words 'sessionCount[someNumber]" ?
I tried the array_keys function in php, but that requires an exact word match, meaning I would need to know the number following 'sessionCount' in the key, so I'd need to get all the keys that contain that word first somehow.
$tmp = array();
foreach ($array as $sub)
foreach ($sub as $k => $v)
if (substr($k, 0, 12) == 'sessionCount')
$tmp[$k] = $v;
Perhaps something like this will help.
$myArray = array(37) { [0]=> // I get 37 arrays returned
array(10) { ["groupId"]=> string(1) "3" // the first param is just an id
["sessionCount84"]=> string(1) "0"
["sessionCount1"]=> string(1) "1" } ...
$sessions = array();
array_map(function($session) use (&$sessions) {
foreach ($session as $key => $value) {
if ($key starts with "sessionCount") // I'm going to leave that up to you
$sessions[$key] = $value;
}
}, $myArray);
without changing the array you can only do this by brute force.. aka. try "sessionCount[0-999]"..
a different approach would be to use strcmp() on the array keys like so:
foreach($array as $key => $value)
if(!strcmp($key,"sessionCount"))
dosomething($key,$value);
or loop through your array once and restructure it to something like this:
array() {
["sessionCount"] => array() {
[84] => "",
[1] => "",
}
}
..after that finding all the keys you require should be a walk in the park. ;)