How to urlencode a multidimensional array? - php

I have searched hi and low for a solution. I have a dynamic multidimensional array I need to break up and urlencode. The number of items will change but they will always have the same keys.
$formFields = Array (
[0] => Array ( [form_name] => productID [form_value] => 13 )
[1] => Array ( [form_name] => campaign [form_value] => email#gmail.com )
[2] => Array ( [form_name] => redirect [form_value] => http://example.com ) )
Each array has a Form Name and a Form Value.
This is what I'm trying to get to:
$desired_results =
productID => 13
campaign => email#gmail.com
redirect => http://example.com
Every time I try and split them up I end up with: form_name => productID or something like that.
I'm trying to take the results and then urlencode them:
productID=13&campaign=email&gmail.com&redirect=http://example.com&

you can use serialize and the unserialize:
$str = urlencode(serialize($formFields));
and then to decode it:
$formFields = unserialize(urldecode($str));

This will return the values regardless of the names of the keys.
$result = array();
foreach ($formFields as $key => $value)
{
$tmp = array_values($value);
$result[$tmp[0]] = $tmp[1];
}
print(http_build_query($result));
The foreach loops through the main array, storing the subarrrays in the variable $value. The function array_values return all the values from each array as a new numeric array. The value of [form_name] will be stored in the first index, [form_value] in the second.
The built in http_build_query function will return a urlencoded string.

Here's my straightforward function for doing such a thing:
function array_urlencode($data) {
if (is_array($data)) {
foreach($data as $k => $v) $data_temp[urlencode($k)]=array_urlencode($v);
return $data_temp;
} else {
return urlencode($data);
}
}

<!-- Encode entire array here -->
function encode(&$item, $key) {
$item = rawurlencode($item);
}
array_walk_recursive($input_array, 'encode');

Related

Values From Multi-Row MySQL To Single Array

Fetching multi-row data from MySQL database and trying to convert the results into a single array. Since the data is coming from a custom function where modifying it will break many other things, I can't change the way the way it is fetched so must process after retrieval using PHP. This is a sample:
Array
(
[0] => Array
(
[FieldLabel] =>
[FieldName] => ID
[FieldValue] => $ID
[FieldType] => 0
)
[1] => Array
(
[FieldLabel] => Name
[FieldName] => Name
[FieldValue] => $FieldName
[FieldType] => 1
)
)
Looking for something like this with only all the values in a single array but with the variables populated:
Array('','ID',$ID,0,'Name','Name',$FieldName,1)
I found this little function in another post that seemed would at lease create the array it but unfortunately it does not and I don't know enough about array manipulation to be able to sort it out. Any ideas?
function array2Recursive($array) {
$lst = array();
foreach( array_keys($array) as $k ) :
$v = $array[$k];
if (is_scalar($v)) :
$lst[] = $v;
elseif (is_array($v)) :
$lst = array_merge($lst,array2Recursive($v));
endif;
endforeach;
return array_values(array_unique($lst));
}
On way to solve this could be to use a foreach to loop through the items and add them to an array:
$result = [];
foreach ($array as $a) {
foreach($a as $item) {
$result[] = $item;
}
}
print_r($result);
Demo

PHP: How can I get the value from a key in a multiple array

The multiple array looks like
Array
(
[id] => description
[header] =>
[width] => 20
[dbfield] => description
[type] => text
)
Array
(
[id] => quantity
[header] => Menge
[dbfield] => QUANTITY_NEW
[width] => 60
[type] => decimal
)
How can I get the value from dbfield where id is 'quantity' without knowing the numeric value of the id?
The actual code looks like
foreach($array as $id => $fieldData) {
if($fieldData['type'] == 'decimal')
{
doSomething...();
}
}
In the part with doSomething I need access to other fields from the array, but I only know the id. I already tried it with dbfield['quantity']['dbfield'] etc. which obviously fails.
A simple alternative using array_keys:
function getValues($data, $lookForValue, $column)
{
$res = array();
foreach ($data as $key => $data)
{
if($idx = array_keys($data, $lookForValue))
{
$res[$idx[0]] = $data[$column];
}
}
return $res;
}
$values = getValues($myData, "quantity", "dbfield");
var_dump($values);
echo out the array as such..
$array = array();
$array['qty'] = 'qtty';
$array['dbfield'] = 'QUANTITY_NEW';
if($array['qty'] = 'qtty'){
echo $array['dbfield'];
}
returns - QUANTITY_NEW
You can do this with several methods, one of them is using array_map to get those values:
$dbfield = array_filter(array_map(function($a){
if($a["id"] === "quantity"){
return $a["dbfield"];
}
}, $array));
print_r($dbfield);
You iterate over the array, and return the key dbfield where id is 'quantity'. Array filter is just to not return null values where it doesn't have 'quantity' id.
Online attempt to reproduce your code can be found here

Using mysql_real_escape_string in a multidimensional array in php

I am working on a big script which will generate some string or array or multidimensional array i want use mysql_real_escape_string for all array / string
for that this i tried the below code
function check($data) {
if(!is_array($data)) {
return mysql_real_escape_string($data);
} else if (is_array($data)) {
$newData = array();
foreach($data as $dataKey => $dataValue){
if(!is_array($dataValue)){
$key = mysql_real_escape_string($dataKey);
$value = mysql_real_escape_string($dataValue);
$newData[$key] = $value;
}
}
return $newData;
}
}
if i use like this check('saveme'); this returns value
if i pass a array it returns corrent value [ check(array('a','b','c',1,2,3)) ]
if i pass multidimensional array i get [check(array(array('a',array('a','b','c',1,2,3),'c',1,2,3),'b',array('a','b','c',1,2,3),1,2,3))]
A kind note i want to use mysql_real_escape_string for array key too.
You can use array_walk_recursive function, to go throw all leaves of the array, and escape values:
array_walk_recursive($array, function(&$leaf) {
if (is_string($leaf))
$leaf = mysql_real_escape_string($leaf);
});
Also, it is good to follow data consistency rules, and do not use !is_array(), but is_string(), because mysql_real_escape_string takes string params, not !string.
Unfortunately, array_walk_recursive is designed so, that it can't edit keys. If you need edit keys, you may want to write your own recursive function. I don't want to copy answer, you can find it here
You can use this function :
(MyStringEscapeFunc() is your custom escape function)
function escape_recursive($arr){
if(is_array($arr)){
$temp_arr = array();
foreach ($arr as $key=>$value){
$temp_arr[MyStringEscapeFunc($key)] = escape_recursive($value);
}
return $temp_arr;
}else{
return MyStringEscapeFunc($arr);
}
}
Example Result :
//Before :
Array (
[0] => Array (
[0] => foo'bar
[1] => bar'baz
)
[1] => foob'ar
[2] => Array ( [foo'baz] => baz'foo )
)
//After :
Array (
[0] => Array (
[0] => foo\'bar
[1] => bar\'baz
)
[1] => foob\'ar
[2] => Array ( [foo\'baz] => baz\'foo )
)

search associative array by value

I'm fetching some JSON from flickrs API. My problem is that the exif data is in different order depending on the camera. So I can't hard-code an array number to get, for instance, the camera model below. Does PHP have any built in methods to search through associative array values and return the matching arrays? In my example below I would like to search for the [label] => Model and get [_content] => NIKON D5100.
Please let me know if you want me to elaborate.
print_r($exif['photo']['exif']);
Result:
Array
(
[0] => Array
(
[tagspace] => IFD0
[tagspaceid] => 0
[tag] => Make
[label] => Make
[raw] => Array
(
[_content] => NIKON CORPORATION
)
)
[1] => Array
(
[tagspace] => IFD0
[tagspaceid] => 0
[tag] => Model
[label] => Model
[raw] => Array
(
[_content] => NIKON D5100
)
)
[2] => Array
(
[tagspace] => IFD0
[tagspaceid] => 0
[tag] => XResolution
[label] => X-Resolution
[raw] => Array
(
[_content] => 240
)
[clean] => Array
(
[_content] => 240 dpi
)
)
$key = array_search('model', array_column($data, 'label'));
In more recent versions of PHP, specifically PHP 5 >= 5.5.0, the function above will work.
To my knowledge there is no such function. There is array_search, but it doesn't quite do what you want.
I think the easiest way would be to write a loop yourself.
function search_exif($exif, $field)
{
foreach ($exif as $data)
{
if ($data['label'] == $field)
return $data['raw']['_content'];
}
}
$camera = search_exif($exif['photo']['exif'], 'model');
$key = array_search('Model', array_map(function($data) {return $data['label'];}, $exif))
The array_map() function sends each value of an array to a user-made function, and returns an array with new values, given by the user-made function. In this case we are returning the label.
The array_search() function search an array for a value and returns the key. (in this case we are searching the returned array from array_map for the label value 'Model')
This would be fairly trivial to implement:
$model = '';
foreach ($exif['photo']['exif'] as $data) {
if ($data['label'] == 'Model') {
$model = $data['raw']['_content'];
break;
}
}
foreach($exif['photo']['exif'] as $row) {
foreach ($row as $k => $v) {
if ($k == "label" AND $v == "Model")
$needle[] = $row["raw"];
}
}
print_r($needle);
The following function, searches in an associative array both for string values and values inside other arrays. For example , given the following array
$array= [ "one" => ["a","b"],
"two" => "c" ];
the following function can find both a,b and c as well
function search_assoc($value, $array){
$result = false;
foreach ( $array as $el){
if (!is_array($el)){
$result = $result||($el==$value);
}
else if (in_array($value,$el))
$result= $result||true;
else $result= $result||false;
}
return $result;
}
$data = [
["name"=>"mostafa","email"=>"mostafa#gmail.com"],
["name"=>"ali","email"=>"ali#gmail.com"],
["name"=>"nader","email"=>"nader#gmail.com"]];
chekFromItem($data,"ali");
function chekFromItem($items,$keyToSearch)
{
$check = false;
foreach($items as $item)
{
foreach($item as $key)
{
if($key == $keyToSearch)
{
$check = true;
}
}
if($check == true)
{break;}
}
return $check;}
As far as I know , PHP does not have in built-in search function for multidimensional array. It has only for indexed and associative array. Therefore you have to write your own search function!!

PHP multidimensional array to simple array

Which method is best practice to turn a multidimensional array
Array ( [0] => Array ( [id] => 11 ) [1] => Array ( [id] => 14 ) )
into a simple array? edit: "flattened" array (thanks arxanas for the right word)
Array ( [0] => 11 [1] => 14 )
I saw some examples but is there an easier way besides foreach loops, implode, or big functions? Surely there must a php function that handles this. Or not..?
$array = array();
$newArray = array();
foreach ( $array as $key => $val )
{
$temp = array_values($val);
$newArray[] = $temp[0];
}
See it here in action: http://viper-7.com/sWfSbD
Here you have it in function form:
function array_flatten ( $array )
{
$out = array();
foreach ( $array as $key => $val )
{
$temp = array_values($val);
$out[] = $temp[0];
}
return $out;
}
See it here in action: http://viper-7.com/psvYNO
You could use array_walk_recursive to flatten an array.
$ret = array();
array_walk_recursive($arr, function($var) use (&$ret) {
$ret[] = $var;
});
var_dump($ret);
If you have a multidimensional array that shouldn't be a multidimensional array (has the same keys and values) and it has multiple depths of dimension, you can just use recursion to loop through it and append each item to a new array. Just be sure not to get a headache with it :)
Here's an example. (It's probably not as "elegant" as xdazz", but it's an alternate without using "use" closure.) This is how the array might start out like:
Start
array (size=2)
0 =>
array (size=1)
'woeid' => string '56413072' (length=8)
1 =>
array (size=1)
'woeid' => string '56412936' (length=8)
Then you might want to have something like this:
Target
array (size=2)
0 => string '56413072' (length=8)
1 => string '56412936' (length=8)
You can use array_walk_recursive
Code
$woeid = array();
array_walk_recursive($result['results']['Result'], function ($item, $key, $woeid) {
if ($key == 'woeid') {
$woeid[] = $item;
}
}, &$woeid);

Categories