Get an EXACT value in $_POST array - php

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.

Related

convert Object inside a string to array

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));

Search for array row with specific column value and return another value from qualifying row

I have a multidimensional array that I am trying to search for a specific value (url) and then retrieve an another value in the same row (value). I also need to divert to an else if it is not found.
array(2) {
[0]=> array(2) {
["url"]=> string(7) "fareham"
["value"]=> string(7) "Fareham"
}
[1]=> array(2) {
["url"]=> string(11) "southampton"
["value"]=> string(11) "Southampton"
}
}
I have been experimenting with array_key_exists() and isset() to check it's set and just coming up null!
For example, if I search for fareham, I want to return Fareham. If I search for nottingham, I expect null.
How can I isolate the qualifying value?
Use array_column() to index the data by the url columns and then use isset() to check if the value is there...
$data = array_column($data, "value", "url");
$search = 'southampton';
$value = isset($data[$search])?$data[$search]:"not found";
echo $value;
or for PHP 7+, you can use the null coalescing operator (??)
$value = $data[$search]??"not found";
Here is the minimal way to do it (no checks)
$a = array (
0 =>
array (
"url" => 'fareham',
"value" => 'Fareham'
),
1 =>
array (
"url" => 'southampton',
"value" => 'Southampton'
)
);
$u = 'fareham';
$i = $a[false===($f=array_search($u,array_column($a,'url')))?-1:$f]['value'];
print_r($i);
Output
Fareham
Sandbox
How it works
First we create an array we can search by using array_column on the column we want to search in this case url. It looks like this [0=>'fareham', 1=>'southampton']
Then we use the normal array_search which returns an index, if you notice above the indexes are correlated to the original array. Which means we can put that in as the top level key, then it's a simple matter of adding the key we want.
Because array_search can return a boolean(false) which PHP sees as 0 or the first index I put a little hack in for that. But a better way is to check it like this:
$a = array (
0 =>
array (
"url" => 'fareham',
"value" => 'Fareham',
"extra" => 'Foo'
),
1 =>
array (
"url" => 'southampton',
"value" => 'Southampton',
"extra" => 'Bar'
)
);
function serchMultiDimensionalValue($needle, $haystack, $fields='value'){
if(false === ($f=array_search($needle,array_column($haystack,'url')))) return false; //or return [];
if(!is_array($fields)) $fields = [$fields];
return array_intersect_key($haystack[$f], array_flip($fields));
}
var_dump(serchMultiDimensionalValue('foo',$a));
var_dump(serchMultiDimensionalValue('fareham',$a));
var_dump(serchMultiDimensionalValue('fareham',$a, 'extra'));
var_dump(serchMultiDimensionalValue('fareham',$a, ['extra','url']));
Ouput
bool(false)
array(1) {
["value"]=>
string(7) "Fareham"
}
array(1) {
["extra"]=>
string(3) "Foo"
}
array(2) {
["url"]=>
string(7) "fareham"
["extra"]=>
string(3) "Foo"
}
Sandbox
I added a bit more "functionality" to it, hope you don't mind.
While it might be alluring to seek out a one-liner like:
array_column($array, $returnColumn, $haystackColumn)[$needle] ?? null
Be aware that array_column() will be unconditionally doubling the memory usage (because it is generating a new array with the same length as the original) for the sake of assigning new first level keys to search by.
Metaphorically speaking, it is like building a new registry of residences in a neighborhood including every homeowner's name and their address. Yes, you can find out who lives at a given home without knocking on the front door, but you had to knock on every door to collect every home's details before enjoying this convenience. Why not just knock on the door of each original house and ask if they are who you are looking for? It is much easier, and you will be able to "quit" early as soon as you find the homeowner that you are looking for.
For best efficiency and for least memory usage, I recommend the below classic loop with conditional break. It is built with dynamic search and return variables for general usage, but you can use hardcoded values if you like.
Code: (Demo)
$array = [
["url" => 'fareham', "value" => 'Fareham'],
["url" => 'southampton', "value" => 'Southampton']
];
$needle = 'fareham';
$haystackColumn = 'url';
$returnColumn = 'value';
$value = null;
foreach ($array as $row) {
if ($row[$haystackColumn] === $needle) {
$value = $row[$returnColumn];
break;
}
}
var_export($value); // 'Fareham'

Add json object to php array

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;

Push Associate array into another array

I would like to push an associate array into another array but I an not sure how to go about it. At the minute I have the following:
$rate_info = array(
"hotel_rating" => $hotel->{'hotelRating'},
"room_rate" => $hotel->{'RoomRateDetailsList'}->{'RoomRateDetails'}->{'RateInfo'}->{'ChargeableRateInfo'}->{'#total'},
"currency" => $hotel->{'RoomRateDetailsList'}->{'RoomRateDetails'}->{'RateInfo'}->{'ChargeableRateInfo'}->{'#currencyCode'},
"deep_link" => $hotel->{'deepLink'}
);
array_push($hotel_array[$hotel->{'name'}]["offers"], "expedia" => $rate_info );
"Offers" is an array , all I want to do is add an key value with an array within in. Any ideas? All I seem to be getting at the minute is parse errors.
UPDATE
This is the output of the array so far
["offers"]=>
array(2) {
["LateRooms"]=>
array(4) {
["hotel_rating"]=>
int(4)
["room_rate"]=>
string(6) "225.06"
["currency"]=>
string(3) "USD"
}
[0]=>
string(4) "test"
}
As you can see instad of [0] I would like ["site"]=>array()
Thanks
Oliver
I'd do this for the array assignment:
$hotel_array[$hotel->name]['offers']['expedia'] = $rate_info;
Ensure your warnings are enabled, so you know arrays (and subarrays) have been set up before you use them.
Did you first do this?
$hotel_array[$hotel->{'name'}] = array();
And then you can do:
array_push($hotel_array[$hotel->{'name'}]["offers"], "expedia" => $rate_info );

Get specific key value pair from multidimensional array

I have the following array:
array(2) {
[0] => array(3) {
["submission_id"] => int(28)
["date"] => string(22) "2010-10-18 15:55:33+02"
["user_id"] => int(12)
}
[1] => array(3) {
["submission_id"] => int(37)
["date"] => string(22) "2010-11-21 16:02:07+01"
["user_id"] => int(23)
}
I want to get only the user_id key values from this array. I could obviously loop over it, but I was wondering if there was a quicker way.
You could use array_map (might not be quicker though, as it will make a function call per array element):
function getUserId($a) {
return $a['user_id'];
}
$user_ids = array_map('getUserId', $array);
Apart from that, looping is the only way (array_map makes loop anyway).
You can access only the user_id values like this if you know the array index you want to access:
$arr = your array here..
echo $arr[0]['user_id'];
echo $arr[1]['user_id'];

Categories