Values From Multi-Row MySQL To Single Array - php

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

Related

Combine one value from an array to all the values of another array php

For the building of a url query I need to combine one value(key) of an array to all the values(value) of another array. Each combined key => value needs to be added to an array.
The problem here is that I can combine the values of the two arrays in two foreach statements, but it creates for every instance a new array.
Update
Having duplicates is impossible so mine initial output is correct.
$array1 array(
[0] => music
[1] => product
)
$array2 array(
[0] => '));waitfor delay '0:0:TIME'--1
[1] => '[TAB]or[TAB]sleep(TIME)='
)
public static function create_combined_array($array1, $array2)
{
$newArray = array();
foreach ($array1 as $key){
//key = [music]
foreach ($array2 as $value) {
//one of the values is = '));waitfor delay '0:0:__TIME__'--1
array_push($newArray, [$key => $value]);
}
}
return $newArray;
}
Implementation
$query_array = Utils::create_combined_array($params, $payload_lines);
print_r($query_array);
$query = http_build_query($query_array);
$this->url = $baseUrl . '?' . $query;
Build query output
protocol://localhost:8000?music='));waitfor delay '0:0:TIME'--1
Sample output
[54] => Array
(
[music] => ));waitfor delay '0:0:__TIME__'--[LF]1
)
[55] => Array
(
[music] => '));waitfor delay '0:0:__TIME__'--1
)
[56] => Array
(
[music] => '));waitfor delay '0:0:__TIME__'--[LF]1
)
[57] => Array
(
[music] => "));waitfor delay '0:0:__TIME__'--1
)
What I wanted to achieve is impossible in PHP.
Example duplicates
Array(
[music] => "));waitfor delay '0:0:__TIME__'--1
[music] => '/**/or/**/benchmark(10000000,MD5(1))#1
)
Use code below:
public static function create_combined_array($array1, $array2)
{
$newArray = array();
foreach ($array1 as $key){
foreach ($array2 as $i => $value) {
$newArray[$i][$key] = $value;
}
}
return $newArray;
}
The key line is $newArray[$i][$key] = $value;. It appends an array to the $newArray at $i index which is the index of your second array $array2.

Replace key of array with the value of another array while looping through

I have two multidimensional arrays. First one $properties contains english names and their values. My second array contains the translations. An example
$properties[] = array(array("Floor"=>"5qm"));
$properties[] = array(array("Height"=>"10m"));
$translations[] = array(array("Floor"=>"Boden"));
$translations[] = array(array("Height"=>"Höhe"));
(They are multidimensional because the contains more elements, but they shouldn't matter now)
Now I want to translate this Array, so that I its at the end like this:
$properties[] = array(array("Boden"=>"5qm"));
$properties[] = array(array("Höhe"=>"10m"));
I have managed to build the foreach construct to loop through these arrays, but at the end it is not translated, the problem is, how I tell the array to replace the key with the value.
What I have done is this:
//Translate Array
foreach ($properties as $PropertyArray) {
//need second foreach because multidimensional array
foreach ($PropertyArray as $P_KiviPropertyNameKey => $P_PropertyValue) {
foreach ($translations as $TranslationArray) {
//same as above
foreach ($TranslationArray as $T_KiviTranslationPropertyKey => $T_KiviTranslationValue) {
if ($P_KiviPropertyNameKey == $T_KiviTranslationPropertyKey) {
//Name found, save new array key
$P_KiviPropertyNameKey = $T_KiviTranslationValue;
}
}
}
}
}
The problem is with the line where to save the new key:
$P_KiviPropertyNameKey = $T_KiviTranslationValue;
I know this part is executed correctly and contains the correct variables, but I believe this is the false way to assing the new key.
This is the way it should be done:
$properties[$oldkey] = $translations[$newkey];
So I tried this one:
$PropertyArray[$P_KiviPropertyNameKey] = $TranslationArray[$T_KiviTranslationPropertyKey];
As far as I understood, the above line should change the P_KiviPropertyNameKey of the PropertyArray into the value of Translation Array but I do not receive any error nor is the name translated. How should this be done correctly?
Thank you for any help!
Additional info
This is a live example of the properties array
Array
(
[0] => Array
(
[country_id] => 4402
)
[1] => Array
(
[iv_person_phone] => 03-11
)
[2] => Array
(
[companyperson_lastname] => Kallio
)
[3] => Array
(
[rc_lot_area_m2] => 2412.7
)
[56] => Array
(
[floors] => 3
)
[57] => Array
(
[total_area_m2] => 97.0
)
[58] => Array
(
[igglo_silentsale_realty_flag] => false
)
[59] => Array
(
[possession_partition_flag] => false
)
[60] => Array
(
[charges_parkingspace] => 10
)
[61] => Array
(
[0] => Array
(
[image_realtyimagetype_id] => yleiskuva
)
[1] => Array
(
[image_itemimagetype_name] => kivirealty-original
)
[2] => Array
(
[image_desc] => makuuhuone
)
)
)
And this is a live example of the translations array
Array
(
[0] => Array
(
[addr_region_area_id] => Maakunta
[group] => Kohde
)
[1] => Array
(
[addr_town_area] => Kunta
[group] => Kohde
)
[2] => Array
(
[arable_no_flag] => Ei peltoa
[group] => Kohde
)
[3] => Array
(
[arableland] => Pellon kuvaus
[group] => Kohde
)
)
I can build the translations array in another way. I did this like this, because in the second step I have to check, which group the keys belong to...
Try this :
$properties = array();
$translations = array();
$properties[] = array("Floor"=>"5qm");
$properties[] = array("Height"=>"10m");
$translations[] = array("Floor"=>"Boden");
$translations[] = array("Height"=>"Höhe");
$temp = call_user_func_array('array_merge_recursive', $translations);
$result = array();
foreach($properties as $key=>$val){
foreach($val as $k=>$v){
$result[$key][$temp[$k]] = $v;
}
}
echo "<pre>";
print_r($result);
output:
Array
(
[0] => Array
(
[Boden] => 5qm
)
[1] => Array
(
[Höhe] => 10m
)
)
Please note : I changed the array to $properties[] = array("Floor"=>"5qm");, Removed a level of array, I guess this is how you need to structure your array.
According to the structure of $properties and $translations, you somehow know how these are connected. It's a bit vague how the indices of the array match eachother, meaning the values in $properties at index 0 is the equivalent for the translation in $translations at index 0.
I'm just wondering why the $translations array need to have the same structure (in nesting) as the $properties array. To my opinion the word Height can only mean Höhe in German. Representing it as an array would suggest there are multiple translations possible.
So if you could narrow down the $translations array to an one dimensional array as in:
$translation = array(
"Height"=>"Höhe",
"Floor"=>"Boden"
);
A possible loop would be
$result = array();
foreach($properties as $i => $array2) {
foreach($array2 as $i2 => $array3) {
foreach($array3 as $key => $value) {
$translatedKey = array_key_exists($key, $translations) ?
$translations[$key]:
$key;
$result[$i][$i2][$translatedKey] = $value;
}
}
}
(I see every body posting 2 loops, it's an array,array,array structure, not array,array ..)
If you cannot narrow down the translation array to a one dimensional array, then I'm just wondering if each index in the $properties array matches the same index in the $translations array, if so it's the same trick by adding the indices (location):
$translatedKey = $translations[$i][$i2][$key];
I've used array_key_exists because I'm not sure a translation key is always present. You have to create the logic for each case scenario yourself on what to check or not.
This is a fully recursive way to do it.
/* input */
$properties[] = array(array("Floor"=>"5qm", array("Test"=>"123")));
$properties[] = array(array("Height"=>"10m"));
$translations[] = array(array("Floor"=>"Boden", array("Test"=>"Foo")));
$translations[] = array(array("Height"=>"Höhe"));
function array_flip_recursive($arr) {
foreach ($arr as $key => $val) {
if (is_array($val)) {
$arr[$key] = array_flip_recursive($val);
}
else {
$arr = #array_flip($arr);
}
}
return $arr;
}
function array_merge_it($arr) {
foreach ($arr as $key => $val) {
if (is_array($val)) {
$arr[$key] = array_merge_it($val);
} else {
if(isset($arr[$key]) && !empty($arr[$key])) {
#$arr[$key] = $arr[$val];
}
}
}
return $arr;
}
function array_delete_empty($arr) {
foreach ($arr as $key => $val) {
if (is_array($val)) {
$arr[$key] = array_delete_empty($val);
}
else {
if(empty($arr[$key])) {
unset($arr[$key]);
}
}
}
return $arr;
}
$arr = array_replace_recursive($properties, $translations);
$arr = array_flip_recursive($arr);
$arr = array_replace_recursive($arr, $properties);
$arr = array_merge_it($arr);
$arr = array_delete_empty($arr);
print_r($arr);
http://sandbox.onlinephpfunctions.com/code/d2f92605b609b9739964ece9a4d8f389be4a7b81
You have to do the for loop in this way. If i understood you right (i.e) in associative array first key is same (some index).
foreach($properties as $key => $values) {
foreach($values as $key1 => $value1) {
$propertyResult[] = array($translations[$key][$key1][$value1] => $properties[$key][$key1][$value1]);
}
}
print_r($propertyResult);

Retrieve subarray of array by key value

I have the following array (example, real one is larger)
Array
(
[0] => Array
(
[984ab6aebd2777ff914e3e0170699c11] => Array
(
[id] => 984ab6aebd2777ff914e3e0170699c11
[message] => Test1
)
[1] => Array
(
[ca403872d513404291e914f0cad140de] => Array
(
[id] => ca403872d513404291e914f0cad140de
[message] => Test2
)
)
[2] => Array
(
[ca403872d513404291e914f0cad140de] => Array
(
[id] => ca403872d513404291e914f0cad140de
[message] => Test3
)
[3] => Array
(
[ca403872d513404291e914f0cad140de] => Array
(
[id] => ca403872d513404291e914f0cad140de
[message] => Test4
)
)
)
Now I want to somehow "access" the subarray with a given id, e.g. access the subarray with ID 984ab6aebd2777ff914e3e0170699c11 and then proceed to use this array in a foreach like this..
foreach ($array_with_specific_id as $event) {
echo $event['message'];
}
Is this possible?
Edit:
DB code to produce array in my model:
public function get_event_timeline($id)
{
$data = array();
foreach ($id as $result) {
$query = $this->db->query("SELECT * FROM event_timeline WHERE id = ?", array($result['id']));
foreach ($query->result_array() as $row)
{
array_push($data, array($row['id'] => $row));
}
}
return $data;
}
When populating your array from the database you can cerate an additional $index array like the following scheme:
$index = array (
'984ab6aebd2777ff914e3e0170699c11' => ReferenceToElementInData,
'ca403872d513404291e914f0cad140de' => ReferenceToElementInData,
// ...
)
This can give you quick access to the elements via their id without an additional foreach loop. Of course it will need additional memory, but this should be ok as you will only save refrences to the original data. However, test it.
Here comes an example:
public function get_event_timeline($id)
{
$data = array();
// create an additional index array
$index = array();
// counter
$c=0;
foreach ($id as $result) {
$query = $this->db->query("SELECT * FROM event_timeline WHERE id = ?", array($result['id']));
// every entry in the index is an array with references to entries in $data
$index[$result['id']] = array();
foreach ($query->result_array() as $row)
{
array_push($data, array($row['id'] => $row));
// create an entry in the current index
$index[$row['id']][] = &$data[$c];
$c++;
}
}
return array (
'data' => $data,
'index' => $index
);
}
Now you can access the elements via the index array without an additional foreach loop:
$entry = $index['984ab6aebd2777ff914e3e0170699c11'][0];
If there are multiple results per $id (as you mentioned in the comments you can access them using index greater then zero:
$entry = $index['984ab6aebd2777ff914e3e0170699c11'][1];
$entry = $index['984ab6aebd2777ff914e3e0170699c11'][2];
You can get the count of items per $id by calling
$number = count($index['984ab6aebd2777ff914e3e0170699c11']);
That's much the same like indexes that where used in databases to speed up queries.
I'd probably just get rid of the containing array as it seems unnecessary. However, you could do something like:
function get_message($specific_id, $arrays) {
foreach($arrays as $array) {
if(in_array($specific_id, $array)) {
return $array['message'];
}
}
}
I haven't had a chance to test this, but it should work.
function doTheJob($inputArray, $lookingFor) {
foreach ($inputArray as $subArray) {
foreach ($subArray as $subKey => $innerArray) {
if ($subKey == $lookingFor) {
return $innerArray;
}
}
}
return NULL;
}
Alternatively, you can use array_filter instead of outer foreach.

multi array usage in foreach loop

I've got the following array stored in a $_SESSION
[Bookings] => Array
(
[date] => Array
(
[0] => 1/12/2013
[1] => 1/19/2013
[2] => 2/03/2013
)
[price] => Array
(
[0] => 100
[1] => 150
[2] => 120
)
)
However I want to use a foreach loop and perform calculation on both values within the array.I can't seem to fugure out how I can use the foreach to accomodate multivalues, I've got a sample of a foreach I wrote below of what I'm trying to achieve. Anyone point me in the right direction.
foreach ($_SESSION['Bookings'] as $bookings)
{
myDate = $bookings[date];
myPrice = $bookings[price];
// Some other stuff here
}
foreach ($_SESSION['Bookings']['date'] as $key => $value) {
$myDate = $value;
$myPrice = $_SESSION['Bookings']['price'][$key];
}
simpler I guess :)
foreach (array_keys($_SESSION['Bookings']['date']) as $key)
{
$myDate = $_SESSION['Bookings']['date'][$key];
$myPrice = $_SESSION['Bookings']['price'][$key];
}
Should work?
Some info on: array_keys
just loop through on of your subarrays and read the corresponding value from the other
foreach ( $_SESSION['Bookings'][ 'date' ] as $key => $myDate) {
$myPrice = $_SESSION['Bookings'][ 'price' ][ $key ];
// here you can access to $myDate and $myPrice
// Some other stuff here
}

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!!

Categories