This question already has answers here:
How to swap keys with values in array?
(6 answers)
Closed 6 years ago.
How would you modify the following code using only a foreach loop by replacing the keys as the values? For examples the salad, chicken, and pancakes keys would the values instead.
$meals = array(
'Lunch' => array(
'salad' => 'italian',
'salad2' => 'ranch',
'salad3' => 'sesame',
'salad4' => 'bluecheese'
),
'Dinner' => array(
'chicken' => 'grilled',
'chicken2' => 'baked',
'chicken3' => 'steamed',
'chicken4' => 'fried',
'chicken5' => 'broiled'
),
'Breakfast' => array(
'pancakes' => 'blueberry',
'pancakes2' => 'cherry',
'pancakes3' => 'strawberry',
'pancakes4' => 'lemon'
)
);
$newkey = array();
foreach($meals as $key => $value) {
unset($value);
// foreach ($)...
}
print_r($meals);
Edit
If you're unable to use array_flip(), then you'll need to do two loops: one for each meal, and one for each meal option.
Example:
foreach ($meals as $meal => $mealOptions)
{
$revisedMealOptions = array();
foreach ($mealOptions as $originalKey => $newKey)
{
$revisedMealOptions[$newKey] = $originalKey;
}
$meals[$meal] = $revisedMealOptions;
}
Original Answer
It's not entirely clear what you're after. If all you want is to turn:
'Lunch' => array(
'salad' => 'italian'
);
into
'Lunch' => array(
'italian' => 'salad'
);
use array_flip().
Example:
$meals['Lunch'] = array_flip($meals['Lunch']);
See http://php.net/manual/en/function.array-flip.php.
I'm sorry I am a total beginner. I need to use a nested $foreach loop to address this question. For class I'm not allowed to use the array_flip function. I have tried
$newkey = array();
foreach($meals as $key => $value) {
$newkey[] = $value;
foreach ($value as ){
}
}
So, it would read:
Basically I need it to read:
Array(
[Lunch] => array(
[italian] => salad,
[ranch] => salad2,
[sesame] => salad3,
[bluecheese] => salad4
)
)
The easiest way to do it would be like this:
$meals = array(
'Lunch' => array(
'salad' => 'italian',
'salad2' => 'ranch',
'salad3' => 'sesame',
'salad4' => 'bluecheese'
),
'Dinner' => array(
'chicken' => 'grilled',
'chicken2' => 'baked',
'chicken3' => 'steamed',
'chicken4' => 'fried',
'chicken5' => 'broiled'
),
'Breakfast' => array(
'pancakes' => 'blueberry',
'pancakes2' => 'cherry',
'pancakes3' => 'strawberry',
'pancakes4' => 'lemon'
)
);
$newArray = array();
foreach ($meals as $key => $value) {
$temp = array();
foreach ($value as $innerKey => $innerValue) {
$temp[$innerValue] = $innerKey;
}
$newArray[$key] = $temp;
}
unset($meals);
Basically, you create a new array and build it from the beginning with the use of the array $meals.
Related
How can I make the values of array comma separated values?
this is my array:
array(
'product_name' =>
0 => 'pn1',
1 => 'pn2'
'supply_product_name' =>
0 => 'ps1'
'custom_product_code' =>
0 => string 'cpc1'
)
how to achieve to look like these:
array(
'product_name' => 'pn1, pn2' ,
'supply_product_name' => 'ps1' ,
'custom_product_code' => 'cpc1'
)
Try these code:
$arr = array(
'product_name' => ['pn1', 'pn2'],
'supply_product_name' => ['ps1'],
'custom_product_code' => ['cpc1']
);
foreach($arr as $key => $val)
{
$arr[$key] = implode($val, ',');
}
var_dump($arr);
I am trying to validate an associative array pushed from my JavaScript, using the validation library.
The following code is working except it is only validating (finding the values) for the last array within the associative array, is there a way for it to work for each instance of the array as it runs in the foreach?
code:
if (!empty($JSON)) {
foreach ($JSON AS $k => $data) {
foreach ($data AS $key => $value) {
$this->form_validation->set_data($data);
if($key == 'itemCode' . $k){
$this->form_validation->set_rules($key, 'Item Code', 'required');
}
if($key == 'Desc' . $k){
$this->form_validation->set_rules($key, 'Description', 'required');
}
if($key == 'Qty' . $k){
$this->form_validation->set_rules($key, 'Quantity', 'required|numeric');
}
if($key == 'Cost' . $k){
$this->form_validation->set_rules($key, 'Cost', 'required|numeric');
}
}
//$this->form_validation->reset_validation();
}
}
array output:
[0] => Array(
[Counter0] => 0
[itemCode0] => 1
[Desc0] => 1
[Qty0] => 1
[Cost0] => 1
[Total0] => 1
)
[1] => Array(
[Counter1] => 1
[itemCode1] => 2
[Desc1] => 2
[Qty1] => 2
[Cost1] => 2
[Total1] => 4
)
[2] => Array(
[Counter2] => 2
[itemCode2] => 3
[Desc2] => 3
[Qty2] => 3
[Cost2] => 3
[Total2] => 9
)
[3] => Array(
[Counter3] => 3
[itemCode3] => 4
[Desc3] => 4
[Qty3] => 4
[Cost3] => 4
[Total3] => 16
)
The problem is, the set_data function gets called between the set_rules function and according to CI
You have to call the set_data() method before defining any validation rules.
For more information take a look at the documentation
A possible method would be to catch all data and rules in an array
Below is an example how to achieve that, pls keep in mind i haven't tested it because i wrote it here down but you should be able to see the point
$arrValidationData = array();
$arrValidationRules = array();
$arrCatchValidationData = array(
"itemCode" => array(
"label" => "Item Code",
"rules" => "required"
),
"Desc" => array(
"label" => "Description",
"rules" => "required"
),
"Qty" => array(
"label" => "Quantity",
"rules" => "required|numeric"
),
"Cost" => array(
"label" => "Cost",
"rules" => "required|numeric"
),
);
if (!empty($JSON)) {
foreach ($JSON AS $k => $data) {
foreach ($data AS $key => $value) {
$keyToCatch = str_replace($k, "", $key);
if (isset($arrCatchValidationData[$keyToCatch]))
{
$arrValidationData[$key] = $value;
$arrValidationRules[] = array(
"field" => $key,
"label" => $arrCatchValidationData[$keyToCatch]['label'],
"required" => $arrCatchValidationData[$keyToCatch]['rules']
);
}
}
//$this->form_validation->reset_validation();
}
$this->form_validation->set_data($arrValidationData);
$this->form_validation->set_rules($arrValidationRules);
}
update: 30.05.2016
according to your comment you want to validate post and json data in the same call, in this case you simply have to merge the data
$arrValidationData = array_merge($arrValidationData, $_POST);
I want to delete array index which contain rating 0 here is my array
array(
(int) 0 => array(
'Gig' => array(
'id' => '1',
'rating' => (int) 5
)
),
(int) 1 => array(
'Gig' => array(
'id' => '3',
'rating' => (int) 9
)
),
(int) 2 => array(
'Gig' => array(
'id' => '4',
'rating' => '0'
)
)
)
and what I did
for($i = 0; $i<count($agetGigsItem); $i++)
{
if($agetGigsItem[$i]['Gig']['rating']==0)
{
unset($agetGigsItem[$i]);
}
$this->set('agetGigsItem', $agetGigsItem);
}
i also try foreach loop but unable to resolve this issue.
foreach ($agetGigsItem as $key => $value) {
if ($value["Gig"]["rating"] == 0) { unset($agetGigsItem[$key]); }
}
I think you need to reupdate your array.
foreach ($agetGigsItem as $key => $value) {
if ($value["Gig"]["rating"] != 0)
{
unset($agetGigsItem[$key]);
}
$this->set('agetGigsItem', $agetGigsItem);
}
I hope you are missing $this and so you cannot access the array in CakePHP.
So try this:
foreach ($this->$agetGigsItem as $key => $value) {
if ($value["Gig"]["rating"] == 0) {
unset($this->$agetGigsItem[$key]);
}
}
This code will unset arrey index with value 0.
<?php
$array=array(
array(
'Gig' => array(
'id' => '1',
'rating' =>5
)
),
array(
'Gig' => array(
'id' => '3',
'rating' =>9
)
),
array(
'Gig' => array(
'id' => '4',
'rating' =>0
)
)
);
foreach($array as $a){
if($a['Gig']['rating']==0){
unset($a['Gig']['rating']);
}
$array1[]=$a;
}
var_dump($array1);
Destroying occurances within an array you are actually processing over with a for or a foreach is always a bad idea. Each time you destroy an occurance the loop can easily get corrupted and get in a terrible mess.
If you want to remove items from an array it is better to create a copy of the array and process over that new array in the loop but remove the items from the original array.
So try this instead
$tmparray = $this->agetGigsItem; // will copy agetGigsItem into new array
foreach ($tmparray as $key => $value) {
if ($value["Gig"]["rating"] == 0) {
unset($this->agetGigsItem[$key]);
}
}
unset($tmparray);
when searching an element in a nested array, could i get back it's 1st level nesting index.
<?php
static $cnt = 0;
$name = 'victor';
$coll = array(
'dep1' => array(
'fy' => array('john', 'johnny', 'victor'),
'sy' => array('david', 'arthur'),
'ty' => array('sam', 'joe', 'victor')
),
'dep2' => array(
'fy' => array('natalie', 'linda', 'molly'),
'sy' => array('katie', 'helen', 'sam', 'ravi', 'vipul'),
'ty' => array('sharon', 'julia', 'maddy')
)
);
function recursive_search(&$v, $k, $search_query){
global $cnt;
if($v == $search_query){
/* i want the sub array index to be returned */
}
}
?>
i.e to say, if i'am searching 'victor', i would like to have 'dep1' as the return value.
Could anyone help ??
Try:
$name = 'victor';
$coll = array(
'dep1' => array(
'fy' => array('john', 'johnny', 'victor'),
'sy' => array('david', 'arthur'),
'ty' => array('sam', 'joe', 'victor')
),
'dep2' => array(
'fy' => array('natalie', 'linda', 'molly'),
'sy' => array('katie', 'helen', 'sam', 'ravi', 'vipul'),
'ty' => array('sharon', 'julia', 'maddy')
)
);
$iter = new RecursiveIteratorIterator(new RecursiveArrayIterator($coll), RecursiveIteratorIterator::SELF_FIRST);
/* These will be used to keep a record of the
current parent element it's accessing the childs of */
$parent_index = 0;
$parent = '';
$parent_keys = array_keys($coll); //getting the first level keys like dep1,dep2
$size = sizeof($parent_keys);
$flag=0; //to check if value has been found
foreach ($iter as $k=>$val) {
//if dep1 matches, record it until it shifts to dep2
if($k === $parent_keys[$parent_index]){
$parent = $k;
//making sure the counter is not incremented
//more than the number of elements present
($parent_index<$size-1)?$parent_index++:'';
}
if ($val == $name) {
//if the value is found, set flag and break the loop
$flag = 1;
break;
}
}
($flag==0)?$parent='':''; //this means the search string could not be found
echo 'Key = '.$parent;
Demo
This works , but I don't know if you are ok with this...
<?php
$name = 'linda';
$col1=array ( 'dep1' => array ( 'fy' => array ( 0 => 'john', 1 => 'johnny', 2 => 'victor', ), 'sy' => array ( 0 => 'david', 1 => 'arthur', ), 'ty' => array ( 0 => 'sam', 1 => 'joe', 2 => 'victor', ), ), 'dep2' => array ( 'fy' => array ( 0 => 'natalie', 1 => 'linda', 2 => 'molly', ), 'sy' => array ( 0 => 'katie', 1 => 'helen', 2 => 'sam', 3 => 'ravi', 4 => 'vipul', ), 'ty' => array ( 0 => 'sharon', 1 => 'julia', 2 => 'maddy', ), ), );
foreach($col2 as $k=>$arr)
{
foreach($arr as $k1=>$arr2)
{
if(in_array($name,$arr2))
{
echo $k;
break;
}
}
}
OUTPUT :
dept2
Demo
I'm trying to add a key and value (associative) from an array to another array, where one specific key and value match. Here are the two arrays:
$array1 = array(
1 => array(
'walgreens' => 'location',
'apples' => 'product1',
'oranges' => 'product2'
),
2 => array(
'walmart' => 'location',
'apples' => 'product1',
'oranges' => 'product2',
'milk' => 'product3'
)
);
$array2 = array(
1 => array(
'walgreens' => 'location',
'apples' => 'product1',
'oranges' => 'product2',
'bananas' => 'product3',
)
);
Here is the attempt I made at modifying $array1 to have key 'bananas' and value 'product3':
$dataCJ = getCJItem($isbn);
foreach ($array1 as $subKey => $subArray) {
foreach($subArray as $dkey => $dval){
foreach($array2 as $cjk => $cjv){
foreach($cjv as $cjkey => $cjval){
if($dval['walgreens'] == $cjval['walgreens']){
$dval['bananas'] = $cjval['bananas'];
}
}
}
}
}
This doesn't work. How can I fix this?
Change => $dval to => &$dval. Currently you are creating and writing to a new variable and the update will not work in-place.
I would look at array_merge() function!
Here is a start with the PHP doc.
For your specific case, you could do the following :
foreach($array1 as $key1 => $values1){
foreach($array2 as $key2 => $values2){
if($values1[0] == $values2[0]){
$array1[$key1] = array_merge($values1, $values2);
}
}
}
Note to simplify the problem you should inverse the first key=> value pair of the array.
Having an array this way would be a lot simper :
array(
'location' => "The location (eg:walgreens)",
//...
);
This way you could change the comparison to the following instead :
$values1['location'] == $values2['location']
Which would be safer in the case the array is not built with the location as the first pair.