Lets say I have an multidimensional string array:
.food = array(
'vegetable' => array(
'carrot' => 'blablue',
'potato' => 'bluebla',
'cauliflower' => 'blabla'
),
'Fruit' => array(
'apple' => 'chicken65',
'orange' => 'salsafood',
'pear' => 'lokkulakka'
)
);
is it possible to access the array by using index as numbers, instead of using the name of the key?
So for accessing chicken65 , I will type echo $food[1][0]; I don't want to use numbers as key, because its a big array and its more user-friendly if I use string as key and it will let me do for-loops on advanced level.
You can do foreach loops to achieve much the same thing as a typical for-loop.
foreach ($foods as $key => $value) {
//For the first iteration, $key will equal 'vegetable' and $value will be the array
}
$food[1][0] != $food[1]['apple'], so you cannot use numeric keys in this case.
try
$new_array = array_values($food);
however, variable can't start with .. It should start with $
you may want to try the function array_values but since you are dealing with multidemsional arrays, here is a solution posted by a php programmer
http://www.php.net/manual/en/function.array-values.php#103905
but it would be easier to use foreach instead of for.
You can use array_keys() on the array. The resulting array can be traversed via a for-loop and gives you the associative key.
I will show it to you for the first dimension:
$aTest = array('lol' => 'lolval', 'rofl' => 'roflval');
$aKeys = array_keys($aTest);
$iCnt = count($aKeys);
for($i = 0; $i < $iCnt; ++$i)
{
var_dump($aTest[$aKeys[$i]]);
}
You would need to do this for two dimensions but I would not recommend this. It is actually more obstrusive and slower than most other solutions.
I don't think there is something native to go this route.
And it does seem like you are trying to stretch array use a bit.
You should go OOP on this one.
Create a FoodFamilly object and a Food object in which you can store arrays if necessary and you'll be able to write a nice user-friendly code and add indices if needed.
OOP is almost always the answer :)
Related
I have the following array that is supposed to only be keys:
$keys = ['mod_4_key'];
and the bigger array which contains a lot of information:
$big_array = [ 'mod_4_key' => ['old' => '', 'info' => ''], 'mod_5_key' => ..]
I would like to, based on what is inside $keys generate a new array with the information from $big_array, as such, if we are to compute the "non-difference" between the arrays, the output should be:
$final_array = [ 'mod_4_key' => ['old' => '', 'info' => '']]
I achieved this using a classic foreach but I was wondering if there was no in-built way to achieve this.
You may be better off with a simple foreach() loop, but there are probably several ways of achieving this.
This uses array_flip() on the $keys, so that you end up with another associative array, then use array_intersect_key() with the big array first.
$final_array = array_intersect_key($big_array, array_flip($keys));
Is there a standard PHP function that changes an associative array's index names?
$a1 = array('one'=>1,'two'=>2,'three'=>3);
$new_index_names = array('one'=>'ono','two'=>'dos','three'=>'tres');
$a2 = change_index_names($a1,$new_index_names);
print_r($a2);
// $a2 should have the index names changed accordingly and look like this:
// array('ono'=>1,'dos'=>2,'tres'=>3)
EDIT
Please note that the function needs to know the mappings to the new index names. Meaning, in $new_index_names array provides the mappings. So again, it needs to know that 'ono' is the new index name for 'one'.
EDIT
I know you guys can come up with your own solution, i was wondering there is a standard PHP function that already does this.
EDIT
There are several situations where changing index names would help:
1) separates post value names to generic/internal names so you can separate
your backend code from front-end code.
2) say for instance you have two arrays from post that need to go through the
same exact process, except both arrays although mean/contain same exact type
of values/order/structure, they're index names are different. So when
passing to a function/method that goes by only a set of index names, you'll
need to convert the index names before passing them to that function/method.
You don't need array_values To get your desired output you can just use
array_combine($new_index_names,$a1);
not in just 1 function, but you could use array_values to get the values of the first array, and array_combine to set the new keys
Assuming both arrays has equal count, one way is with array_combine() and array_values()
$a2 = array_combine(array_values($new_index_names), $a1);
The previous answers does not consider the order of $a1 and $new_index_names, so I put my solution following:
$a1 = array('one' => 1, 'two' => 2, 'three' => 3, 'zero' => 0);
$new_index_names = array('zero' => 'zero', 'one' => 'ono', 'two' => 'dos', 'three' => 'tres');
array_combine(
$new_index_names,
str_replace(array_keys($a1), array_values($a1), array_keys($new_index_names))
);
Array
(
[zero] => 0
[ono] => 1
[dos] => 2
[tres] => 3
)
The best answer I've seen thus far:
foreach ($a1 as $k => $v) $a2[$new_index_names[$k]] = $v;
Credits go to jh1711
Using the numbers from $ids, I want to pull the data from $nuts.
So for example:
$ids = [0,3,5]; // 0 calories, 3 sugar, 5 fat
$nuts = [
'calories' => 'cal',
'protein' => 'pro',
'carbohydrate' => 'car',
'sugar' => 'sug',
'fiber' => 'fib',
'fat' => 'fat',
];
$returnData = [
'calories' => 'cal',
'sugar' => 'sug',
'fat' => 'fat',
];
I could loop through each $ids number with a foreach(); but I'm curious to see if there is a better method than this?
$newNuts = array_values(array_flip($nuts));
foreach($ids as $i)
$returnData[$newNuts[$i]] = $nuts[$newNuts[$i]];
I did some work and realized, you don't need array_flip, array_values is fine.
$num_nuts = array_values ($nuts);
for ($z=0; $z<sizeof($ids); $z++) {
echo $num_nuts[$ids[$z]];
}
Just 1 more line of code, but I think it does the job. I think mine is going to be faster because the array_flip basically exchanges all keys with their associated values in an array, which is not what I am doing. It's actually one less pain.
I am simply converting the original array to a new one by index and simply looping upon it. Also, not the elegant way to use the power of PHP available to us, but works just fine. array_flip is O(n), but I think better not use it for larger data-sets.
How about a simple array_slice?
$result = array();
foreach ($ids as $i) {
$result += array_slice($nuts, $i, 1, true);
}
No need to create a copy of the array.
I have two arrays, which I can either do the simple approach, which is do a For Each loop on each array, and if one way is the method, accept it, or vice-versa, or is it possible to set values in an array with the same key value?
Like:
<?php
$Array = Array('UniqueValue' => 'Key',
'UniqueValue_2' => 'Key',
'DifferentValue' => 'Key_2'); // and etc...
?>
I could probably try trial and error, but another method would be somehow integrating the arrays and only reading the values I need?
Thanks for your guys' time.
ah, quick edit. I feel like someone's going to bring this up, so I read Nested array, get items with same key and I tried, but it's not working for me. It reads only the first value, and I'm not breaking the loop. If you want to see the code I'm working with, I'll gladly add it.
Actually, I found a better way to word this, so!
I need to iterate through each array value with the same key in a For Each loop.
Like so:
ForEach($Array as $Key){ // or $Key => $Value
If($Key == 'Key'){
Echo $Value;
}
}
<?php
$Array = Array(
0 => Array('Test', 'Testing', 'Tester'),
1 => Array('Test2'));
Print_R($Array[0]); // Array ( [0] => Test [1] => Testing [2] => Tester )
?>
Ah, I forgot about nesting arrays. Sorry about that, haha, but for anyone who would possibly need an answer, here you go.
array(
[0]
name => 'joe'
size => 'large'
[1]
name => 'bill'
size => 'small'
)
I think i'm being thick, but to get the attributes of an array element if I know the value of one of the keys, I'm first looping through the elements to find the right one.
foreach($array as $item){
if ($item['name'] == 'joe'){
#operations on $item
}
}
I'm aware that this is probably very poor, but I am fairly new and am looking for a way to access this element directly by value. Or do I need the key?
Thanks,
Brandon
If searching for the exact same array it will work, not it you have other values in it:
<?php
$arr = array(
array('name'=>'joe'),
array('name'=>'bob'));
var_dump(array_search(array('name'=>'bob'),$arr));
//works: int(1)
$arr = array(
array('name'=>'joe','a'=>'b'),
array('name'=>'bob','c'=>'d'));
var_dump(array_search(array('name'=>'bob'),$arr));
//fails: bool(false)
?>
If there are other keys, there is no other way then looping as you already do. If you only need to find them by name, and names are unique, consider using them as keys when you create the array:
<?php
$arr = array(
'joe' => array('name'=>'joe','a'=>'b'),
'bob' => array('name'=>'bob','c'=>'d'));
$arr['joe']['a'] = 'bbb';
?>
Try array_search
$key = array_search('joe', $array);
echo $array[$key];
If you need to do operations on name, and name is unique within your array, this would be better:
array(
'joe'=> 'large',
'bill'=> 'small'
);
With multiple attributes:
array(
'joe'=>array('size'=>'large', 'age'=>32),
'bill'=>array('size'=>'small', 'age'=>43)
);
Though here you might want to consider a more OOP approach.
If you must use a numeric key, look at array_search
You can stick to your for loop. There are not big differences between it and other methods – the array has always to be traversed linearly. That said, you can use these functions to find array pairs with a certain value:
array_search, if you're there's only one element with that value.
array_keys, if there may be more than one.