how to assign id based on array values - php

I am learning php please help.
I am storing values in an array and then I am trying to get the id of another array checking the value in array like this:
$arr_folders = ['one', 'two', 'whatever'];
$id_one = '';
$id_two = '';
$id_whatever = '';
foreach ($tree as $key => $value) {
if($value['name'] == 'one'){//how to check dynamically?
$id_one = $value['id'];
}
if($value['name'] == 'two'){//how to check dynamically?
$id_two = $value['id'];
}
if($value['name'] == 'whatever'){//how to check dynamically?
$id_whatever = $value['id'];
}
}
echo $id_whatever;
How can I check the arrays values dynamically. I mean I want to check if the value exist in array then assign their id.

You need to use in_array to check whether the element is exist or not in another array, and if found you can create dynamic variable based on $value['name'] containing $value['id'] as required.
$tree = [
['id' => 1, 'name' => 'one'],
['id' => 2, 'name' => 'two'],
['id' => 3, 'name' => 'three']
];
$arr_folders = ['one', 'two', 'whatever'];
foreach ($tree as $key => $value) {
if (in_array($value['name'], $arr_folders)) {
${'id_'.$value['name']} = $value['id'];
}
}
echo $id_one;
Working Example: https://eval.in/596034
Note: make sure $value['name'] doesn't contain spaces or any other characters which aren't allowed to declare variable names.

Try using array search
For example:
<?php
$arr_folders = ['one', 'two', 'whatever'];
foreach ($tree as $key => $value) {
if (($key = array_search($arr_folders, $value)) !== false) {
return $arr_folders[$key];
}
}
echo $id_whatever;

If I understand the question, you're asking how you can check for the contents of one array (in this case, [one, two, whatever]) in the middle of looping through the other array without hardcoding it. If that's the case, I might try something like this:
$arr_folders = ['one', 'two', 'whatever'];
$id_folders = ['', '', '']
foreach ($tree as $key => $value) {
foreach ($arr_folders as $fkey => $fvalue) { // f for folder, in this case
if($value['name'] == $fvalue){
$id_folders[$fkey] = $value['id'];
}
}
}
echo $id_folders[2];
There may be other more elegant or time-effficient solutions, but I think this captures the dynamic nature you're looking for while mirroring the actual process of the previous code.

here is sample code :
<?php
$arr_folders = ['one', 'two', 'whatever'];
$tree= Array(Array('id' => 1,'name' => 'one'),
Array('id' => 2,'name' => 'large'),
Array('id' => 3,'name' => 'thumb'),
Array('id' => 4,'name' => 'two'),
Array('id' => 5,'name' => 'large'),
Array('id' => 6,'name' => 'thumb')
);
foreach ($tree as $key => $value) {
if(in_array($value['name'],$arr_folders)){
$searchedIds[] = $value['id'];
}
}
print_r($searchedIds);
?>

Related

How to sum column value or multiple values in multi-dimensional array?

How can I add all the columnar values by associative key? Note that key sets are dynamic and some key value is more than one.
Example array :
$myArray = array(
["apple" => 2,"orange" => 1,"lemon" => 4,"grape" => 5],
["apple" => 5,"orange" => 0,"lemon" => 3,"grape" => 2],
["apple" => 3,"orange" => 0,"lemon" => 1,"grape" => 3],
);
With single key value I can sum the column value easily with the code below.
$sumArray = array();
foreach ($myArray as $k => $subArray)
{
foreach ($subArray as $id => $value)
{
if (array_key_exists($id, $sumArray))
{
$sumArray[$id] += $value;
} else {
$sumArray[$id] = $value;
}
}
}
echo json_encode($sumArray);
the result will be like these:
{"apple":10,"orange":1,"lemon":8,"grape":10}
For multiple key values the code above is not working. How to sum column values if key value is more than one?
Example array:
$myArraymulti = array(
["apple" => 2,"orange" => 1,"lemon" => [4, 2],"grape" => 5],
["apple" => 5,"orange" => [0, 2],"lemon" => 3,"grape" => 2],
["apple" => 3,"orange" => 0,"lemon" => 1,"grape" => [3, 8]],
);
Desired result:
{"apple":10,"orange":3,"lemon":10,"grape":18}
Check if the value is an array. If it is, use the sum of the elements instead of the value itself when adding to the associative array.
foreach ($myArray as $k => $subArray)
{
foreach ($subArray as $id => $value)
{
if (is_array($value)) {
$value_to_add = array_sum($value);
} else {
$value_to_add = $value;
}
if (array_key_exists($id, $sumArray))
{
$sumArray[$id] += $value_to_add;
} else {
$sumArray[$id] = $value_to_add;
}
}
}
I suggest you fix your data structure, though. You should just make every value an array, rather than mixing singletons and arrays, so you don't have to use conditionals in all the code that processes the data.
$keys = [];
forEach($myArraymulti as $array){
$keys = array_merge(array_keys($array), $keys);
}
$res = [];
forEach(array_unique($keys) as $key){
forEach($myArraymulti as $array){
if(isset($array[$key])){
$res[$key] = (isset($res[$key]) ? $res[$key] : 0) +
(is_array($array[$key]) ? array_sum($array[$key]) : $array[$key]);
}
}
}
$res = json_encode($res));

Error in Array execution in foreach loop :

Someone please help me correcting the errors in this code
This was the code where i am trying to find the names of the icecreams in stock
<?php
$flavors = array();
$flavors[]=array("name" => "CD" , "in_stock" => true);
$flavors[]=array("name" => "V" , "in_stock" => true);
$flavors[]=array("name" => "S" , "in_stock" => false);
foreach($flavors as $flavor => $value) {
if($flavor["in_stock"] == true) {
echo $flavor["name"] . "\n";
}
}
?>
You have flat non-associative array, that means you don't need to iterate using $key => $value but just $item.
So in you case the fix is that simple:
https://ideone.com/j7RMAH
...
// foreach ($flavors as $flavor => $value) {
foreach ($flavors as $flavor) {
...
foreach() - foreach will additionally assign the current element's key to the $key variable on each iteration
foreach (array_expression as $key => $value)
statement
Note: You can use any variable it's not necessary to use the variable with name $key
You are using the key for the condition $flavor["in_stock"] and same for the $flavor["name"]. You need to use $value which holding the current iteration array, correct use of foreach for your code is
foreach($flavors as $flavor => $value) {
if($value["in_stock"] == true) {
echo $value["name"] . "\n";
}
}
Why iterate at all? One can just filter an array with a condition:
<?php
$flavors = [];
$flavors[] = ['name' => 'CD', 'in_stock' => true];
$flavors[] = ['name' => 'V', 'in_stock' => true];
$flavors[] = ['name' => 'S', 'in_stock' => false];
$inStock = array_filter($flavors, function (array $flavor) {
return $flavor['in_stock'];
});
print_r($inStock);
$inStockFlavors = array_column($inStock, 'name');
print_r($inStockFlavors);

Array ksort only shows non-like values?

Have an array for a ranking script.
Some times the key will be the same. They are numeric.
When the sort is ran, only non-like values are echoed.
Can't figure out the fix.
$list = array( $value1 => 'text', $value2 => 'text', $value3 => 'text');
krsort($list);
foreach ($list as $key => $frame) {
echo $frame;
}
If you assign two values to the same key in an array, the first value will be overridden by the second. You'll therefore end up with only one value for that key in the array.
To resolve this, I'd suggest to change your array structure like this:
<?php
$list = array( $key1 => array($key1member1, $key2member2),
$key2 => array($key2member1),
$key3 => array($key3member1, $key3member2, $key3member3) );
krsort($list);
foreach ($list as $key => $frames) {
foreach ($frames => $frame) {
echo $frame;
}
}
?>
Going by what you wrote in the comments to this question and my other answer, I'd recommend to switch keys and values.
<?php
$list = array( "frame1" => 4, "frame2" => 2, "frame3" => 99, "frame4" => 42 );
arsort($list);
foreach ($list as $frame => $ranking) {
echo $frame;
}
?>

Add elements to all empty keys of an array

I use the following code to fill all empty keys in sub-arrays with ``:
$array = array(
'note' => array('test', 'test1'),
'year' => array('2011','2010', '2012'),
'type' => array('conference', 'journal', 'conference'),
);
foreach ($array['type'] as $k => $v) {
foreach($array as $element => $a) {
$iterator = $array[$element];
if(!isset($iterator[$k])){
$iterator[$key] = '';
}
}
}
print_r($array);
The problem is that it is not actually changing the elements in $array but in temporary variable $iterator.
I know that this is a simple question but I would like to find out the best and fastest solution.
You don't need the $iterator variable, you can do just:
foreach ($array['type'] as $k => $v) {
foreach($array as $element => $a) {
if(!isset($array[$element][$k])){
$array[$element][$key] = '';
}
}
}
I would also recommending switching the inner and outer loops, so it's more readable and more efficient.
foreach($array as $element => $a) {
foreach ($array['type'] as $k => $v) {
if(!isset($array[$element][$k])){
$array[$element][$key] = '';
}
}
}
Looks like you have some typos. $key in the middle of the loops is never defined.
$a should be the same value as $iterator[$k], so no need to set it.
Try this.
$array = array(
'note' => array('test', 'test1'),
'year' => array('2011','2010', '2012'),
'type' => array('conference', 'journal', 'conference'),
);
foreach ($array as $k => $v) {
foreach($k as $element => $a) {
if(!isset($a)){
$array[$element] = '';
}
}
}

PHP rename array keys in multidimensional array

In an array such as the one below, how could I rename "fee_id" to "id"?
Array
(
[0] => Array
(
[fee_id] => 15
[fee_amount] => 308.5
[year] => 2009
)
[1] => Array
(
[fee_id] => 14
[fee_amount] => 308.5
[year] => 2009
)
)
foreach ( $array as $k=>$v )
{
$array[$k] ['id'] = $array[$k] ['fee_id'];
unset($array[$k]['fee_id']);
}
This should work
You could use array_map() to do it.
$myarray = array_map(function($tag) {
return array(
'id' => $tag['fee_id'],
'fee_amount' => $tag['fee_amount'],
'year' => $tag['year']
); }, $myarray);
$arrayNum = count($theArray);
for( $i = 0 ; $i < $arrayNum ; $i++ )
{
$fee_id_value = $theArray[$i]['fee_id'];
unset($theArray[$i]['fee_id']);
$theArray[$i]['id'] = $fee_id_value;
}
This should work.
Copy the current 'fee_id' value to a new key named 'id' and unset the previous key?
foreach ($array as $arr)
{
$arr['id'] = $arr['fee_id'];
unset($arr['fee_id']);
}
There is no function builtin doing such thin afaik.
This is the working solution, i tested it.
foreach ($myArray as &$arr) {
$arr['id'] = $arr['fee_id'];
unset($arr['fee_id']);
}
The snippet below will rename an associative array key while preserving order (sometimes... we must). You can substitute the new key's $value if you need to wholly replace an item.
$old_key = "key_to_replace";
$new_key = "my_new_key";
$intermediate_array = array();
while (list($key, $value) = each($original_array)) {
if ($key == $old_key) {
$intermediate_array[$new_key] = $value;
}
else {
$intermediate_array[$key] = $value;
}
}
$original_array = $intermediate_array;
Converted 0->feild0, 1->field1,2->field2....
This is just one example in which i get comma separated value in string and convert it into multidimensional array and then using foreach loop i changed key value of array
<?php
$str = "abc,def,ghi,jkl,mno,pqr,stu
abc,def,ghi,jkl,mno,pqr,stu
abc,def,ghi,jkl,mno,pqr,stu
abc,def,ghi,jkl,mno,pqr,stu;
echo '<pre>';
$arr1 = explode("\n", $str); // this will create multidimensional array from upper string
//print_r($arr1);
foreach ($arr1 as $key => $value) {
$arr2[] = explode(",", $value);
foreach ($arr2 as $key1 => $value1) {
$i =0;
foreach ($value1 as $key2 => $value2) {
$key3 = 'field'.$i;
$i++;
$value1[$key3] = $value2;
unset($value1[$key2]);
}
}
$arr3[] = $value1;
}
print_r($arr3);
?>
I wrote a function to do it using objects or arrays (single or multidimensional) see at https://github.com/joaorito/php_RenameKeys.
Bellow is a simple example, you can use a json feature combine with replace to do it.
// Your original array (single or multi)
$original = array(
'DataHora' => date('YmdHis'),
'Produto' => 'Produto 1',
'Preco' => 10.00,
'Quant' => 2);
// Your map of key to change
$map = array(
'DataHora' => 'Date',
'Produto' => 'Product',
'Preco' => 'Price',
'Quant' => 'Amount');
$temp_array = json_encode($original);
foreach ($map AS $k=>$v) {
$temp_array = str_ireplace('"'.$k.'":','"'.$v.'":', $temp);
}
$new_array = json_decode($temp, $array);
Multidimentional array key can be changed dynamically by following function:
function change_key(array $arr, $keySetOrCallBack = [])
{
$newArr = [];
foreach ($arr as $k => $v) {
if (is_callable($keySetOrCallBack)) {
$key = call_user_func_array($keySetOrCallBack, [$k, $v]);
} else {
$key = $keySetOrCallBack[$k] ?? $k;
}
$newArr[$key] = is_array($v) ? array_change_key($v, $keySetOrCallBack) : $v;
}
return $newArr;
}
Sample Example:
$sampleArray = [
'hello' => 'world',
'nested' => ['hello' => 'John']
];
//Change by difined key set
$outputArray = change_key($sampleArray, ['hello' => 'hi']);
//Output Array: ['hi' => 'world', 'nested' => ['hi' => 'John']];
//Change by callback
$outputArray = change_key($sampleArray, function($key, $value) {
return ucwords(key);
});
//Output Array: ['Hello' => 'world', 'Nested' => ['Hello' => 'John']];
I have been trying to solve this issue for a couple hours using recursive functions, but finally I realized that we don't need recursion at all. Below is my approach.
$search = array('key1','key2','key3');
$replace = array('newkey1','newkey2','newkey3');
$resArray = str_replace($search,$replace,json_encode($array));
$res = json_decode($resArray);
On this way we can avoid loop and recursion.
Hope It helps.

Categories