Getting values from associative array - php

I have the following main array called $m
Array
(
[0] => Array
(
[home] => Home
)
[1] => Array
(
[contact_us] => Contact Us
)
[2] => Array
(
[about_us] => About Us
)
[3] => Array
(
[feedback_form] => Feedback Form
)
[4] => Array
(
[enquiry_form] => Products
)
[5] => Array
(
[gallery] => Gallery
)
)
I have the values eg home, contact_us in a array stored $options , I need to get the values from the main array called $m using the $options array
eg. If the $options array has value home, i need to get the value Home from the main array ($m)
my code looks as follows
$c = 0;
foreach($options as $o){
echo $m[$c][$o];
++$c;
}
I somehow just can't receive the values from the main array?

I'd first transform $m to a simpler array with only one level:
$new_m = array();
foreach ($m as $item) {
foreach ($item as $key => $value) {
$new_m[$key] = $value;
}
}
Then you can use:
foreach ($options as $o) {
echo $new_m[$o];
}

Try this:
foreach($options as $o){
foreach($m as $check){
if(isset($check[$o])) echo $check[$o];
}
}
Although It would be better TO have the array filled with the only the pages and not a multidimensional array

Assuming keys in the sub arrays are unique you can
merge all sub arrays into a single array using call_user_func_array on array_merge
swap keys and values of your option array
Use array_intersect_key to retrieve an array with all the values.
Example like so:
$options = array('about_us', 'enquiry_form');
$values = array_intersect_key(
call_user_func_array('array_merge', $m), // Merge all subarrays
array_flip($options) // Make values in options keys
);
print_r($values);
which results in:
Array
(
[about_us] => About Us
[enquiry_form] => Products
)

How's this?
foreach( $options as $option )
{
foreach( $m as $m_key => $m_value )
{
if( $option == $m_key )
{
echo 'Name for ' . $options . ' is ' . $m_value;
break;
}
}
}

Try using a recursive array_walk function, for example
$a = array(
array('ooo'=>'yeah'),
array('bbb'=>'man')
);
function get_array_values($item, $key){
if(!is_numeric($key)){
echo "$item\n";
}
}
array_walk_recursive($a,'get_array_values');

Are you sure that the options array is in the same order of $m? Maybe you your
echo $m[$c][$o];
is resolving into a $m[0]['gallery'] which is obviously empty.
you can try different solutions, to me, a nice one (maybe not so efficient) should be like this:
for($c=0, $limit=count($c); $c < $limit; $c++)
if (array_search(key($m[$c]), $options))
echo current($m[$c]);
If you would like to use your approach have to flatten your array with something like this:
foreach ($m as $o)
$flattenedArray[key($o)]=current($o);
foreach ($options as $o)
echo $flattenedArray($o);
Doing this, though, eliminates duplicate voices of your original array if there are such duplicates.

$trails1 = array();
foreach ($trails as $item) {
foreach ($item as $key => $value) {
$trails1[].= $value;
}
}
echo '<pre>';print_r($trails1);
exit;

Related

PHP - Getting Value of Nested Array from Array of Keys

I have the following:
$values = Array (
['level1'] => Array (
['level2'] => Array(
['level3'] => 'Value'
)
)
)
I also have an array of keys:
$keys = Array (
[0] => 'level1',
[1] => 'level2',
[2] => 'level3'
)
I want to be able to use the $keys array so I can come up with: $values['level1']['level2']['level3']. The number of levels and key names will change so I need a solution that will read my $keys array and then loop through $values until I get the end value.
You could iterate over $values and store a $ref like this :
$ref = $values ;
foreach ($keys as $key) {
if (isset($ref[$key])) {
$ref = $ref[$key];
}
}
echo $ref ; // Value
You also could use references (&) to avoid copy of arrays :
$ref = &$values ;
foreach ($keys as &$key) {
if (isset($ref[$key])) {
$ref = &$ref[$key];
}
}
echo $ref ;
<?php
$values['level1']['level2']['level3'] = 'Value';
$keys = array (
0 => 'level1',
1 => 'level2',
2 => 'level3'
);
$vtemp = $values;
foreach ($keys as $key) {
try {
$vtemp = $vtemp[$key];
print_r($vtemp);
print("<br/>---<br/>");
}
catch (Exception $e) {
print("Exception $e");
}
}
Hope this helps. Of course remove the print statements but I tried it and in the end it reaches the value. Until it reaches the values it keeps hitting arrays, one level deeper at a time.

How to make an associative array with elements from an array as its key and use arrays for corresponding values?

I have arrays $devices,$port
print_r($devices);
Array(
[0] => cisco1
[1] => cisco2
)
print_r($port);
Array
(
[0] => Port1/1/1
[1] => Port1/1/10
[2] => Port1/1/11
)
I want to create an array $devlist which would be something like this:
Array(
[cisco1] =>Port1/1/1
Port1/1/10
Port1/1/11
[cisco2] =>Port2/1/1
Port2/1/10
Port2/1/11
)
My point is there is an array of devices($devices) and arrays of ports that are there in each of the device.
The $port array gets created newly for each device in the $device array.
What i have tried so far:
foreach ($devices as $value)
{
$port=();
//iam polling the respective device and getting a list of ports available for that device in array **$port**
array_push($devices[$value], $port);
}
This method generates an error "array_push() expects parameter 1 to be array, null given"
Kindly excuse me if this seems an easy question becoz iam new to php and scripting as well:(
Do you want something like this? If so, i don't understand why, when you could just use the values from $ports for each $device?
$devices = array
(
'cisco1', 'cisco2'
);
$ports = array
(
'Port1/1/1',
'Port1/1/10',
'Port1/1/11'
);
$dev_list = array();
foreach ($devices as $device)
{
$dev_list[$device] = array();
foreach ($ports as $port)
{
array_push($dev_list[$device], $port);
}
}
echo '<pre>';
print_r($dev_list);
echo '</pre>';
Array
(
[cisco1] => Array
(
[0] => Port1/1/1
[1] => Port1/1/10
[2] => Port1/1/11
)
[cisco2] => Array
(
[0] => Port1/1/1
[1] => Port1/1/10
[2] => Port1/1/11
)
)
Try this:
$devlist = array();
foreach ($devices as $value)
{
$port=();
//iam polling the respective device and getting a list of ports available for that device in array **$port**
$devlist[$value] = $port;
}
You may use a foreach or a for loop but the main thing is that you have to use variable variables.
Solution One:
$devlist = array();
foreach($devices as $key => $device){
$devlist[$device] = ${"port".($key+1)};
}
Solution Two:
$devlist = array();
$size = sizeof($devices);
for($i = 0; $i < $size; $i++){
$devlist[$devices[$i]] = ${"port".($i+1)};
}
If I understand your question, you want something like this:
$arr = array
(
'cisco1' => array
(
'Port1/1/1',
'Port1/1/10',
'Port1/1/11'
),
'cisco2' => array
(
'Port1/1/1',
'Port1/1/10',
'Port1/1/11'
)
);
foreach($arr as $key => $value) // use the foreach-loop like this to get both keys and values
{
echo "$key: <br />-" . implode('<br />-', $value) . '<br /><br />';
}
prints:
cisco1:
-Port1/1/1
-Port1/1/10
-Port1/1/11
cisco2:
-Port1/1/1
-Port1/1/10
-Port1/1/11

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

How to setup a PHP multidimensional array and declare the array keys?

I need some help setting up a PHP array. I get a little lost with multidimensional arrays.
Right now, I have an array with multiple products as follows:
If I do: print_r($products['1']); I get:
Array ( [0] => size:large [1] => color:blue [2] => material:cotton )
I can do print_r($products['2']); , etc and it will show a similar array as above.
I am trying to get it where I can do this:
echo $products['1']['color']; // the color of product 1
...and echo "blue";
I tried exploding the string and adding it to the array as follows:
$step_two = explode(":", $products['1']);
foreach( $step_two as $key => $value){
$products['1'][$key] = $value;
}
I know I'm obviously doing the explode / foreach way wrong but I wanted to post my code anyway. I hope this is enough information to help sort this out.
Try this:
foreach ($products as &$product)
{
foreach ($product as $key => $value)
{
list($attribute, $val) = explode(':',$value);
$product[$attribute] = $val;
// optional:
unset($product[$key]);
}
}
?>
Here goes a sample that will convert from your first form to your desired form (output goes below)
<?php
$a = array( '1' => array('color:blue','size:large','price:cheap'));
print_r($a);
foreach ($a as $key => $inner_array) {
foreach ($inner_array as $key2 => $attribute) {
$parts = explode(":",$attribute);
$a[$key][$parts[0]] = $parts[1];
//Optional, to remove the old values
unset($a[$key][$key2]);
}
}
print_r($a);
?>
root#xxx:/home/vinko/is# php a.php
Array
(
[1] => Array
(
[0] => color:blue
[1] => size:large
[2] => price:cheap
)
)
Array
(
[1] => Array
(
[color] => blue
[size] => large
[price] => cheap
)
)
You would be better of to build the array the right way, but to solve your problem you need to explode in the loop, something like:
foreach( $products['1'] as $value){
$step_two = explode(":", $value);
$products['1'][$step_two[0]] = $step_two[1];
}
You can wrap another foreach around it to loop over your whole $products array.
And you'd also better build a new array to avoid having both the old and the new values in your $products array.
You are right: you got the "foreach" and "explode" the wrong way around. Try something like this:
foreach($products['1'] as $param => $value) {
$kv = explode(":", $value);
if(count($kv) == 2) {
$products[$kv[0]] = $kv[1];
unset($products['1'][$param]);
}
}
This code first loops over the sub-elements of your first element, then splits each one by the colon and, if there are two parts, sets the key-value back into the array.
Note the unset line - it removes array elements like $products['1'][1] after setting products['1']['color'] to blue.
If you already have $products structured in that way, you can modifty its structure like this:
$products = array(
'1' => array(
0 => 'size:large', 1 => 'color:blue', 2 => 'material:cotton'
),
'2' => array(
0 => 'size:small', 1 => 'color:red', 2 => 'material:silk'
),
);
foreach ($products as &$product) {
$newArray = array();
foreach ($product as $item) {
list($key, $value) = explode(':', $item);
$newArray[$key] = $value;
}
$product = $newArray;
}
print_r($products);
If you don't want to overwrite original $products array, just append $newArray to another array.
<?php
$products = array();
$new_product = array();
$new_product['color'] = "blue";
$new_product['size'] = "large";
$new_product['material'] = "cotton";
$products[] = $new_product;
echo $products[0]['color'];
//print_r($products);

how to reach into PHP nested arrays?

I've a nested array whose print_r looks like this-
Array
(
[keyId] => Array
(
[hostname] => 192.168.1.127
[results] => Array
(
[1] => false
[2] => false
[3] => false
)
[sessionIDs] => Array
(
[0] => ed9f79e4-2640-4089-ba0e-79bec15cb25b
)
)
I would like to process(print key and value) of the "results" array. How do I do this?
I am trying to use array_keys function to first get all the keys and if key name is "results", process the array. But problem is array_keys is not reaching into the "results"
php's foreach loop is what you need.
foreach($arr['keyId']['results'] as $key => $value) {
//$key contains key and $value contains values.
}
The array you want is $array['keyID']['results']. From there you access the values with $array['keyID']['results'][1], $array['keyID']['results'][2], $array['keyID']['results'][3]
To loop through it just do this:
foreach($array['keyId']['results'] as $key => $value) {
echo $key . ' ' . $value;
}
or
for ($i = 1; $i <= 3; i++)
{
echo $i . ' ' . $array['keyID']['results'][i];
}
foreach($array['keyId']['results'] as $k => $v) {
// use $k and $v
}
One way to navigate through the array is this.
//Assuming, your main array is $array
foreach($array as $value) { //iterate over each item
if(isset($value['results']) && count($value['results'])) {
// ^ check if results is present
//Now that we know results exists, lets use foreach loop again to get the values
foreach($value['result'] as $k => $v) {
//The boolean values are now accessible with $v
}
}
}

Categories