here is the code im having trouble with
$key = array(
"0" => "sss",
"1" => "wst",
"2" => "sfv",
"3" => "lac",
"4" => "sgv",
"5" => "lgb",
"6" => "ant"
);
$urls = array(
"0" => "http://www.sarmenhb.com/index.php?key=",
"1" => "http://www.navidoor.com/index.php?key=",
"2" => "http://www.worldexchange.com/index.php?key=",
"3" => "http://www.iaddesign.com/index.php?key=",
"4" => "http://www.iadesignandstudio.com/index.php?key=",
"5" => "http://www.redlineautoleasing.com/index.php?key="
);
for($a=0;$a <= count($urls);$a++) {
foreach($key as $keys) {
print $urls[$a].$keys[$a]."<br/>";
}
}
print "<br/><br/>";
i am trying to make the output look like this:
http://www.sarmenhb.com/index.php?key=sss
http://www.navidoor.com/index.php?key=sss
http://www.worldexchange.com/index.php?key=sss
http://www.iaddesign.com/index.php?key=sss
http://www.iadesignandstudio.com/index.php?key=sss
http://www.redlineautoleasing.com/index.php?key=sss
http://www.sarmenhb.com/index.php?key=wst
http://www.navidoor.com/index.php?key=wst
http://www.worldexchange.com/index.php?key=wst
http://www.iaddesign.com/index.php?key=wst
http://www.iadesignandstudio.com/index.php?key=wst
http://www.redlineautoleasing.com/index.php?key=wst
etc including all key values included as a value the the param key
ive removed the origional urls to prevent url hacking but how can i print an output like that?
the output i keep getting is key=s or key=w the whole key value isnt displaying. along with an error of Notice: Uninitialized string offset: 3 in D:\wamp\www\MVC\t.php on line 32
please help
thank alot!
foreach($key as $string)
{
foreach($urls as $address)
{
echo $address . $string . "<br/>";
}
}
I would simply do two foreach statements:
foreach($urls as $url) {
foreach($keys as $key) {
print $url.$key."\n";
}
}
I also recommend you to pluralize the name of your arrays for simple readability, check the output here.
That's because you're printing $keys[$a]. $keys is a string from your array, and $a would just get a single character. You can select characters in strings the same way you select variable from array.
If you remove the square brackets it should work.
print $urls[$a].$keys."<br/>";
Remove the foreach loop and change $keys[$a] to $key[$a].
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 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));
This is only for arrays with index number. For example i have this arrays;
$array = [
"0" => "number 1",
"1" => "number 2",
"2" => "number 3",
"3" => "number 4",
"4" => "number 5",
"5" => "number 6",
"6" => "number 7",
"7" => "number 8",
"8" => "number 9"
];
I want to skip the loop from certain range of key indexes for example, skip the foreach if the number of index is from range 0 to 5. That means we can do just like this.
foreach($array as $key => $value){
if(array_key_exist($key, range(0,5))
continue;
echo $value."<br/>"
}
or we can using for... loop
for($ind = 0; $ind < count($array); $ind++){
if(array_key_exist($ind, range(0,5))
continue;
echo $arr[$ind]."<br/>"
}
How could i skip the index without using continue or searching the array_key first ? sure the code above looks fine to me, but if i have a bunch of arrays keys and values, i think this is not a good choice.
You can use array_diff as:
$wantKeys = array_diff(array_keys($array), range(1,5));
Now all you need is loop on the $wantKeys as:
foreach($wantKeys as $k)
echo $array[$k]; // only wanted values
The same idea can be achieve by array_diff_keys:
$wantKeys = array_diff_key($array, array_flip(range(1,5)));
You can get the slice of array from 5th index to rest,
$result = array_slice($array,5,count($array)-5, true);
array_slice — Extract a slice of the array
Note:
array_slice() will reorder and reset the integer array indices by
default. This behaviour can be changed by setting preserve_keys to
TRUE. String keys are always preserved, regardless of this parameter.
Demo.
Here is the example PHP array representation
array(
"test1" => array(
"test1subtest1" => array(..)
),
"test2" => array(
"test2subtest1" => array(..)
)
)
So, here is the question: is there any tool in PHP which can be used to assign values to multidimensional array with random depth and index names? It suppose to look like this:
$valuetoassing = "TESTVALUE";
$testarray = array();
array_assign_multidimensional($testarray, $valuetoassing, array("test1", "test1subtest1", "test1subtest1subtest1"));
Problem is that I do not know what depth the array will have, so I can not code it. Index names are also generated at the run time.
EDIT: I figured that my particular case can be solved using some kind of linked list (stored as array with items that contain actual data and pointer to the index of the next element), but I'm sure I'll meet this problem again in the future so I will not close the question right now.
This is pretty easy to do using references.
function array_assign_multidimensional(&$input_array, $value, $list){
$assignee = &$input_array;
foreach($list as $key){
$assignee = &$assignee[$key];
}
$assignee = $value;
}
$input = array(
'firstLayer' => array(
'secondLayer' => array(
'test' => 'old'
)
),
'randomOutlyingValue' => ''
);
array_assign_multidimensional($input, 'new', array('firstLayer', 'secondLayer', 'test'));
var_dump($input);
/*
array(2) {
["firstLayer"]=>
array(1) {
["secondLayer"]=>
array(1) {
["test"]=>
string(3) "new"
}
}
["randomOutlyingValue"]=>
string(0) ""
}
*/
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. ;)