PHP -> Pick value from two-dimensional array based on key - php

I need to pick a value based on a specific key from an two-dimensional array, how would I do that?
I only know the key of the second level in the array in my code, and not in which array key it sits in level 1...
example:
Array
(
[0] => Array
(
[1] => http://stackoverflow.com/
)
[1] => Array
(
[0] => http://www.google.com
)
[2] => Array
(
[20567] => http://www.yahoo.com
)
)
Now I would like to pick the value of the key 20567 dynamically, I don't know where it sits in level 1, could be 0, 1,2 or any other key.
I hope I explained that well enough :)

You could use a RecursiveArrayIterator and RecursiveIteratorIterator:
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach ($iterator as $key => $value) {
if ($key == 20567) {
var_dump($value);
break;
}
}
Example in a function:
function valueForKey($array, $key) {
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach ($iterator as $arrayKey => $arrayValue) {
if ($arrayKey == $key) {
return $arrayValue
}
}
return null;
}

Another option is: (should work)
function getURLbyRedirects($redirectNumber , $array)
{
foreach($array as $lvl => $elems)
{
if(array_key_exists($redirectNumber , $elems))
return $elems[$redirectNumber];
}
return false;
}
By the way , consider using a different structre for this array, something like this:
Array (
[0] => Array
(
[url] => http://stackoverflow.com/
[redirects] => 2067
)

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.

php - Multidimensional Array To Single dimension Array With Sum Up

I have this array:
Array
(
[one] => Array
(
[a] => 0
[b] => 1
[c] => 1
[d] => 3
[e] => 1
)
[two] => Array
(
[a] => 0
[b] => 3
[c] => 1
[d] => 4
[e] => 1
)
[three] => Array
(
[a] => 3
[b] => 1
[c] => 2
[d] => 4
[e] => 1
)
)
And I want to convert it into single array with the values are the sums of every value inside the inner array, so it could be like this:
Array
(
[a] => 3
[b] => 5
[c] => 4
[d] => 11
[e] => 3
)
How to achieve it?
EDIT
This was the best what I've done:
$rest = array();
foreach($result as $key => $value){
if(is_array($value)) {
foreach($value as $k => $val){
$rest[$k] = array_sum($value);
}
}
}
But it returns all values to be the same, i.e all 9 on every inner key.
You can get the keys from the first child array with array_keys, and then use array_sum and array_column to generate the array of sums.
foreach (array_keys($your_array['one']) as $key) {
$sums[$key] = array_sum(array_column($your_array, $key));
}
array_column does require php >= 5.5.
Incidentally, what you already had was really close to working. If you change
$rest[$k] = array_sum($value);
to
$rest[$k] += $val;
It should be good to go. What you had before was repeatedly summing the entire sub-array and assigning it to each letter key, but you just needed to add the current value to that letter key.
$rest[$k] += $val; will work, but give you undefined index notices for the first sub-array. You can fix that by checking isset before assigning, like this:
$rest[$k] = isset($rest[$k]) ? $rest[$k] + $val : $val;
I would say modifying your original code to work this way would probably be better than redefining array_column if you can't use it.
You have multidimensional Array , that why have to use two loop for understanding in beginning level. First loop will get Every Object of Array , Second Array will get the Params of Object.
$finalArray = array();
for($i = 0;$i<count($array);$i++){ // GET ALL OBJECT FROM ARRAY
foreach($array[$i] as $key=>$value){ // GET ALL KEY FROM OBJECT
$finalArray[$key] += $array[$i][$key];
}
}
print_r($finalArray);
Work on all version of PHP
You can use array_sum and loop over the first dimension
foreach ($array as $key => $values) {
$newArray[$key] = array_sum($values);
}
Credit to Don't Panic's answer above and this answer which is providing array_column() alternative for PHP version < 5.5
// if array_column function don't exist, add array_column function
if (! function_exists('array_column')) {
function array_column(array $input, $columnKey, $indexKey = null) {
$array = array();
foreach ($input as $value) {
if ( ! isset($value[$columnKey])) {
trigger_error("Key \"$columnKey\" does not exist in array");
return false;
}
if (is_null($indexKey)) {
$array[] = $value[$columnKey];
}
else {
if ( ! isset($value[$indexKey])) {
trigger_error("Key \"$indexKey\" does not exist in array");
return false;
}
if ( ! is_scalar($value[$indexKey])) {
trigger_error("Key \"$indexKey\" does not contain scalar value");
return false;
}
$array[$value[$indexKey]] = $value[$columnKey];
}
}
return $array;
}
}
// sum up the values
$rest = array();
foreach($result as $key => $arr){
if(is_array($arr)) {
foreach($arr as $k => $val){
$rest[$k] = array_sum(array_column($result, $k));
}
}
}

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

Array value and index migration

My array is like:
Array
(
[0] => Array
(
[0] => "name"
[1] => "zxczxc5"
)
[1] => Array
(
[0] => "about"
[1] => "zxczxc"
)
[2] => Array
(
[0] => "contact"
[1] => "zxczxc"
)
)
I want to generate another array like this :
Array
{
['name']="zxczxc5";
}
Array
{
['contact']="zxczxc";
}
Array
{
['about']="zxczxc";
}
I want the first array index zero value goes as the index of second value in my new array.
Thanks.
There are many ways to solve what you want to achieve, this is just one of those:
foreach ($array as &$pair) {
$pair = call_user_func_array('array_combine', $pair);
}
unset($pair);
print_r($array);
It makes use of array_combine.
Assuming you name your first Array $aTest:
foreach($aTest as $aElement)
{
$aNewArray[$aElement[0]] = $aElement[1];
}
print_r($aNewArray);
foreach ($array as $value) {
$newArray[$value['0']] = $value['1'];
}
Assuming the first array is called $array
$new_array = array();
foreach($array as $element)
{
$new_array[] = array($element[0] => $element[1]);
}
$newArr = array();
foreach($arr as $val) {
$newArr[$val[0]] = $val[1];
}

Loop an array of array

in PHP, how can i loop an array of array without know if is or not an array?
Better with an example:
Array
(
[0] => Array
(
[0] => big
[1] => small
)
[1] => Array
(
[0] => big
[1] => tiny
)
[2] => Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
[5] => f
)
[3] => row
[4] => cols
[5] => blablabla
[6] => Array
(
[0] => asd
[1] => qwe
)
}
any idea? thanks.
Which approach to choose depends on what you want to do with the data.
array_walk_recursive [docs] lets you traverse an array of arrays recursively.
You can use is_array to check if that element is an array, if it is, loop over it recursively.
You can use is_array to check if something is an array, and/or you can use is_object to check if it can be used within foreach:
foreach ($arr as $val)
{
if (is_array($val) || is_object($val))
{
foreach ($val as $subval)
{
echo $subval;
}
}
else
{
echo $val;
}
}
Another alternative is to use a RecursiveIteratorIterator:
$it = new RecursiveIteratorIterator(
new RecursiveArrayIterator($arr),
RecursiveIteratorIterator::SELF_FIRST);
foreach($it as $value)
{
# ... (each value)
}
The recursive iterator works for multiple levels in depth.
foreach( $array as $value ) {
if( is_array( $value ) ) {
foreach( $value as $innerValue ) {
// do something
}
}
}
That would work if you know it will be a maximum of 2 levels of nested array. If you don't know how many levels of nesting then you will need to use recursion. Or you can use a function such as array_walk_recursive
$big_array = array(...);
function loopy($array)
{
foreach($array as $element)
{
if(is_array($element))
{
// Keep looping -- IS AN ARRAY--
loopy($element);
}
else
{
// Do something for this element --NOT AN ARRAY--
}
}
}
loopy();

Categories