I am using user user input into a form and then it will be searching through this array to see if their input is inside the array. So If a user searches for '45' I need to find its corresponding values in the array.
So if $myArray['Aames'][o] is 45 i need to also find $myArray['Names'][0] and so on. So i need a way to find the element number of '45' and store that number then print out the corresponding information.
$myArray = array
(
"Names"=>array
(
"John",
"Jane",
"Rick"
),
"Speciality"=>array
(
"Buisness",
"sales",
"marketing"
),
"Aames"=>array
(
"45",
"Some guy",
"Another guy"
)
);
$search = '45';
$key = array_search($search, $myArray['Aames']);
$name = $myArray['Names'][$key];
$speciality = $myArray['Speciality'][$key];
echo $name; //Outputs John
echo $speciality; //Outputs Business
You could generalize this a a bit with a function if you plan to apply it more generally.
function searchArray($query, $keyArray, $valuesArray){
$key = array_search($query, $keyArray);
$returnArray = array();
foreach($valuesArray as $arrKey=>$arrVal){
$returnArray[$arrKey] = $arrVal[$key];
}
return $returnArray;
}
$query is a string containing the value you are looking for in $keyArray and $valuesArray is an array of arrays that contain the values associated with the potential query strings.
Example: $userAttributes = searchArray('45', $myArray['Aames'], array('Names'=>$myArray['Names'], 'Speciality'=>$myArray['Speciality']));
$userAttributes should then be array('Names'=>'John', 'Speciality'=>'Buisness') [sic]
Related
I have made a GET call through an API and received data that originally looked like this:
{"#odata.context":"API-URL-CALL","value":[{"Id":1,"Name":Bill"},{"Id":2,"Name":Ted"}]
I took this data and altered it to look like this:
array("Id"=>1,"Name"=>"Bill","Id"=>2,"Name"=>"Ted");
What I am trying to do is echo this all out but so far I have only been able to get the second Id and Name to print out.
My code is as follows:
<?php
$my_array = array("Id"=>1,"Name"=>"Bill","Id"=>2,"Name"=>"Ted");
foreach($my_array as $key => $value)
{
echo
"
$key = $value <br>
";
}
?>
As stated above this only prints out:
Id = 2
Name = Ted
I feel like this is a simple fix and I have looked at many posts but can't seem t find the proper fix for this. I have tried things such as:
$key = $value[0] <br>
$key = $value[0][Id] <br>
foreach($my_array as $arr)
echo
"
id = $arr[Id], <br>
name = $arr[Name]
"
foreach($my_array as $arr)
echo
"
id = $arr[0][Id], <br>
name = $arr[0][Name]
"
All these ever get me are a single character or nothing at all. Like I said before I feel like this is a simple fix and I'm overlooking something or not adding something? Any help or advise or even a link to another post would be much appreciated. Thank you for your time :^D
Not sure how you achieved your second array from the initial JSON (although that has a few errors in the format), but you have flattened the array into a single array which has duplicate keys (and will only end up with the last value).
If you try
print_r(array("Id"=>1,"Name"=>"Bill","Id"=>2,"Name"=>"Ted"));
you would see the data ends up as
Array
(
[Id] => 2
[Name] => Ted
)
To extract the data properly, you need to decode the JSON (corrected JSON in the code) and then extract the data...
$json = '{
"#odata.context": "API-URL-CALL",
"value": [
{
"Id": 1,
"Name": "Bill "
},
{
"Id": 2,
"Name": "Ted"
}
]
}';
$my_array = json_decode($json, true);
foreach ( $my_array['value'] as $arr) {
echo "
id = $arr[Id], <br>
name = $arr[Name]
";
}
You have to put quotes around index names.
foreach($my_array as $arr)
echo '
id = '.$arr['Id'].', <br>
name = '.$arr['Name'].'
';
This happens because you defined associative array. This type of array use key=>value pairs. In this type of array keys should be unique.
Because you used none unique keys for example Id and Name, Every time you insert a value to array it overwrite previous values. So every time you loop through array it just shows last overwrote value.
To fix the problem you should use array inside array:
$my_array = array(array("Id"=>1,"Name"=>"Bill"),array("Id"=>2,"Name"=>"Ted"));
foreach($my_array as $array)
{
echo "{$array['Id']} = {$array['Name']} <br>";
}
I am recently facing a practical problem.I am working with ajax form submission and there has been some checkboxes.I need all checkboxes with same name as key value pair.Suppose there is 4 checkboxes having name attribute =checks so i want something like $arr['checks'] = array(value1, value2, ...)
So i am getting my ajax $_POST code as suppose like: name=alex&checks=code1&checks=code2&checks=code3
I am using below code to make into an array
public function smdv_process_option_data(){
$dataarray = array();
$newdataarray = array();
$new = array();
$notices = array();
$data = $_POST['options']; // data received by ajax
$dataarray = explode('&', $data);
foreach ($dataarray as $key => $value) {
$i = explode('=', $value);
$j = 1;
if(array_key_exists($i[0], $newdataarray)){
if( !is_array($newdataarray[$i[0]]) ){
array_push($new, $newdataarray[$i[0]]);
}else{
array_push($new, $i[1]);
}
$newdataarray[$i[0]] = $new;
}else{
$newdataarray[$i[0]] = $i[1];
}
}
die($newdataarray);
}
Here i want $newdataarray as like below
array(
'name' => 'alex',
'checks => array(code1, code2, code3),
)
But any how I am missing 2nd value from checks key array.
As I see it you only need to do two explode syntaxes.
The first on is to get the name and here I explode on & and then on name= in order to isolate the name in the string.
The checks is an explode of &checks= if you omit the first item with array_slice.
$str = 'name=alex&checks=code1&checks=code2&checks=code3';
$name = explode("name=", explode("&", $str)[0])[1];
// alex
$checks = array_slice(explode("&checks=", $str), 1);
// ["code1","code2","code3"]
https://3v4l.org/TefuG
So i am getting my ajax $_POST code as suppose like: name=alex&checks=code1&checks=code2&checks=code3
Use parse_str instead.
https://php.net/manual/en/function.parse-str.php
parse_str ( string $encoded_string [, array &$result ] ) : void
Parses encoded_string as if it were the query string passed via a URL and sets variables in the current scope (or in the array if result is provided).
$s = 'name=alex&checks=code1&checks=code2&checks=code3';
parse_str($s, $r);
print_r($r);
Output
Array
(
[name] => alex
[checks] => code3
)
You may think this is wrong because there is only one checks but technically the string is incorrect.
Sandbox
You shouldn't have to post process this data if it's sent correctly, as that is not included in the question, I can only make assumptions about it's origin.
If your manually creating it, I would suggest using serialize() on the form element for the data for AJAX. Post processing this is just a band-aid and adds unnecessary complexity.
If it's from a source outside your control, you'll have to parse it manually (as you attempted).
For example the correct way that string is encoded is this:
name=alex&checks[]=code1&checks[]=code2&checks[]=code3
Which when used with the above code produces the desired output.
Array
(
[name] => alex
[checks] => Array
(
[0] => code1
[1] => code2
[2] => code3
)
)
So is the problem here, or in the way it's constructed...
UPDATE
I felt obligated to give you the manual parsing option:
$str = 'name=alex&checks=code1&checks=code2&checks=code3';
$res = [];
foreach(explode('&',$str) as $value){
//PHP 7 array destructuring
[$key,$value] = explode('=', $value);
//PHP 5.x list()
//list($key,$value) = explode('=', $value);
if(isset($res[$key])){
if(!is_array($res[$key])){
//convert single values to array
$res[$key] = [$res[$key]];
}
$res[$key][] = $value;
}else{
$res[$key] = $value;
}
}
print_r($res);
Sandbox
The above code is not specific to your keys, which is a good thing. And should handle any string formatted this way. If you do have the proper array format mixed in with this format you can add a bit of additional code to handle that, but it can become quite a challenge to handle all the use cases of key[] For example these are all valid:
key[]=value&key[]=value //[key => [value,value]]
key[foo]=value&key[bar]=value //[key => [foo=>value,bar=>value]]
key[foo][]=value&key[bar][]=value&key[bar][]=value //[key => [foo=>[value]], [bar=>[value,value]]]
As you can see that can get out of hand real quick, so I hesitate to try to accommodate that if you don't need it.
Cheers!
I have the following URL: myexample.com/?city=Miami
and a large array (23k)
$e = $_GET["city"];
$myArray = array
(
array ("Miami","Florida"),
array ("Key West","Florida"),
array ("NOLA", "Luisiana"),
array ("Baton Rouge","Luisiana")
);
I'm looking for a solution to dynamically create a new array of cities that matches the state of the city in the URL, and echo all the cities from that state.
In other words:
if myexample.com/?city=NOLA, I would like to echo "Baton Rouge" and "NOLA" (from Luisiana)
if myexample.com/?city=Miami, echo "Key West" and "Miami" (from Florida)
etc.
There are quite a few similar questions answered already (here, here, but looping is not one of strengths (beginner).
Thank you.
EDIT1:
$resArray = array();
foreach($myArray as $arr) {
if(in_array($e, $arr))
$resArray[] = $arr;
}
print_r($resArray);
Result: Array ( [0] => Array ( [0] => Miami [1] => Florida ) )
First of all I would restructure your myArray in something like the following:
$stateAndCities = [
"Florida" => ["Miami","Key West"],
"Luisiana" => ["NOLA", "Baton Rouge"]
];
after that you can better handle the input and give an easier output
$city = $_GET["city"];
$resultCities = [];
$resultState = "";
// Loop over all states with their cities
foreach($stateAndCities as $state => $cities) {
if(in_array($city, $cities)){ // if the given $city is in the $cities?
$resultCities = $cities;
$resultState = $state;
break;
}
}
if(!empty($resultState) && !empty($resultCities)){ // ensure that the city was found in any state
echo $resultState;
print_r($resultCities);
}
(the code is not tested!)
Manual:
http://php.net/in_array
http://php.net/empty
So, I have this form that is rather complicated, and the form fields are named to comply with PHP array notation, as such:
<input name='service[123][info]' value=''>
And this of course works as intended and I get the array in $_POST, which I sanitize and then keep in $in. But now I want to reverse-engineer this, when I am iterating over the form again, I have this in $in:
array(
123 => array(
"info" => "foo"
)
)
And when I come to any given form field, I know that the field name is "service[123][info]" but how do I find "foo" in the sent array? Basically, I want to set the value="" parameter in the input when I have data for this field, and the data is kept in the $in array but the only reference to the data I have is the string "service[123][info]". Should I use regexp to parse that string? Sounds inflexible.
Basically, I would like something like:
$name = "service[123][info]";
$value = form_array_lookup($name, $in);
That sets $value to the correct value from $in as referenced by $name. I hope I am making myself clear. Thanks for any comment.
This is a very case-specific (and therefore, not very desirable) example, but the general idea is to use only one delimiter between items, explode the string, and then loop through the result, checking if each item index exists.
function parse_array_path( $string,array $subject ){
// remove ending brackets
$string = str_replace( "]","",$string );
// "[" is now the sole delimiter
$part = explode( "[",$string );
// loop and check for each index in subject array
$i = reset( $part );
do{
if( ! isset( $subject[$i] ) ){
return null;
}
$subject = $subject[$i];
}
while( $i = next( $part ) );
return $subject;
}
example usage:
<?php
$a = array(
"service"=>array(
123=>array(
"info"=>"hello, world"
)
)
);
$s = "service[123][info]";
print parse_array_path( $s,$a ); // "hello, world"
Use a 'foreach' to loop through the array and you can reassign the keys or values in any order you wish.
foreach ($in AS $in_key => $in_val) {
foreach ($in_val AS $in_val_key => $in_val_val) {
// ASSIGN VALUES TO A NEW ARRAY IF YOU WISH
// YOU NOW HAVE $in_key, $in_val_key, $in_val_val
// THAT YOU CAN WORK WITH AND ASSIGN
$array[$in_val_val] = $in_val_key; // OR WHATEVER
}
}
I want to store square bracket string in a variable so that I can use that variable to get the value of array. How can I do that?
Example:
$vehicle = array("car"=>"volvo","bike"=>"polygon");
$bracket1="['car']";
$bracket2="['bike']";
echo $vehicle.$bracket1;//my expected result = 'volvo';
echo $vehicle.$bracket2;//my expected result = 'polygon';
Case
Suppose I have this data
$data = array(
"vehicles"=>array(
array(
"name"=>"volvo",
"manufacturer"=>"abc",
"color"=>array("blue"=>"wonderful","red"=>"fantastic")),
array(
"name"=>"toyota",
"manufacturer"=>"def",
"color"=>array("blue"=>"awesome","red"=>"good")),
array(
"name"=>"mecedes",
"manufacturer"=>"ghi",
"color"=>array("blue"=>"nice","red"=>"great","green"=>"good","brown"=>"elegant")),
));
$fields = array(
"$data['vehicles']['name']",
"$data['vehicles']['manufacturer']",
"$data['vehicles']['color']['blue']",
"$data['vehicles']['color']['red']"
);
//a function to print those data according to user parameter($fields, it may uncertain pattern)
function get_data($data,$fields){
for($c=0;$c<count($data);$c++){
foreach($fields as $field){ //field to show
echo $field;
}
}
}
edited:
$data = array(
"vehicles"=>array(
array(
"name"=>"volvo",
"manufacturer"=>"abc",
"color"=>array("blue"=>"wonderful","red"=>"fantastic")),
array(
"name"=>"toyota",
"manufacturer"=>"def",
"color"=>array("blue"=>"awesome","red"=>"good")),
array(
"name"=>"mecedes",
"manufacturer"=>"ghi",
"color"=>array("blue"=>"nice","red"=>"great","green"=>"good","brown"=>"elegant")),
));
$c=0;
$fields = array( // note added zeros here... these are your "vehicle" array key
"{$data['vehicles'][$c]['name']}",
"{$data['vehicles'][$c]['manufacturer']}",
"{$data['vehicles'][$c]['color']['blue']}",
"{$data['vehicles'][$c]['color']['red']}"
);
for($c=0;$c<count($data['vehicles']);$c++){
foreach($fields as $field) {
echo $field . PHP_EOL;
}
}
//the output print : volvo abc wonderful fantastic volvo abc wonderful fantastic volvo abc wonderful fantastic
//the output expectetd : volvo abc wonderful fantastic toyota dev awesome good mercedes ghi nice great
Why don't you try this:
$vehicle = array("car" => "volvo", "bike" => "polygon");
$bracket1 = "car";
$bracket2 = "bike";
echo $vehicle[$bracket1]; //my expected result = 'volvo';
echo $vehicle[$bracket2]; //my expected result = 'polygon';
Edit: you want a function that does this... You don't need it. This is a basic PHP language construct.
Anywho, here's your function (wrapping that basic PHP language construct up in an extra layer) - I'll even throw in a basic error check (return false if the array key doesn't exist):
function searchMyHugeArrayForSomething($huge_array, $something) {
if(!array_key_exists($something, $huge_array))
return false; // return false if array key doesn't exist
return $huge_array[$something]; // return your desired result......
}
Demo:
$my_huge_array = array(
'pet' => 'cat',
'wife' => 'sarah',
'brother' => 'john'
// etc
);
echo searchMyHugeArrayForSomething($my_huge_array, 'wife'); // sarah
echo searchMyHugeArrayForSomething($my_huge_array, 'husband'); // returns false (oop, sexist!)
echo searchMyHugeArrayForSomething($my_huge_array, 'brother'); // john
// etc............?
Make sense?
Edit: OK, multidimensional array is very different (your original question was flat). You are having an issue here because you're missing a level in between vehicles and name, etc. There's an array there containing numeric indexes, so your path would actually be $data['vehicles'][0]['name'] - and when that's the case, you can basically just echo each line of your array to get the value of the array key parsed into a string.
In this example I've added both curly braces to each line to parse as a variable variable, and because your example won't actually run as it is (it's trying to parse the array keys as a variable and syntactically failing), and added the zero array key. You'll need to work out which array key you want to target yourself, this is just using the first:
$fields = array( // note added zeros here... these are your "vehicle" array key
"{$data['vehicles'][0]['name']}",
"{$data['vehicles'][0]['manufacturer']}",
"{$data['vehicles'][0]['color']['blue']}",
"{$data['vehicles'][0]['color']['red']}"
);
foreach($fields as $field) {
echo $field . PHP_EOL;
}
Output:
volvo
abc
wonderful
fantastic