Array key as variable in foreach - PHP - php

This is probably very simple ... but I can't figure it out. I need to use array keys as variables. I have three tabs that need to use unique variables to access data.
$array = array(
'items' => 'latest',
'itemsFollow' => 'follow',
'itemsExp' => 'expired'
);
while ( ($stuff = current($array)) !== FALSE ) {
echo '<div id="'.key($array).'" class="tab-content grid flex">';
foreach(/*array_key*/ as $item) { //need foreach($items, foreach($itemsFollow and foreach($itemsExp
// do stuff
}
echo '</div>';
next($array);
}

Loop through your array with foreach. There is no need to loop twice (nested loops) in a one dimensional array. Use if, elseif or case statements to do custom stuff depending on the value.
foreach ($array as $key => $value){
echo '<div id="'.$key.'" class="tab-content grid flex">';
if($value=="latest"){
//do stuff
}
elseif($value=="follow"){
//do stuff
}
elseif($value=="expired"){
//do stuff
}
}

Related

Removing an associated key/value pair from array (nested)

I have two function to add remove parameters to the query string. The "add_query_params" (thanks to this forum) is working nicely and I can now add multiple tags to the query string of the same type.
For example
http://example.com?tags[]=flowers&tags[]=shrubs&category[]=garden
As you can see, I can add multiple of the same parameters, I am also querying these nicely using queryfilters.
However my newest problem, is simply removing a single tag type without affecting the rest of the query string. I will then rebuild the query without the deleted tag.
Someone kindly yesterday helped me to to a point but this removes ALL tag key values, not just the specified tag.
So if I was to delete say $tags[]shrubs from the above URL it would actually delete BOTH tag[]shrubs AND $tags[]flowers.
This obviously isn't very intuitive for a filter system I am devising. What I would like to know is how to remove just the single key value pair and leave the other keys pairs intact.
Here is my helper function
//Accept a param array which passthrough through tag type eg category/tag and value
function remove_query_params(array $params = [])
{
//Set to array
$existingParams = [];
$existingParams = request()->query();
foreach($params as $key=>$value){
if (isset($existingParams[$value])) {
unset($existingParams[$value]);
}
}
$query = http_build_query($existingParams);
return url()->current() . '?' . $query;
}
//Need to return: user removes tag from filter in blade, URL recontructs without the passed through tag value
//Before
//http://example.com?tags[]=flowers&tags[]=shrubs&category[]=garden
//After
//http://example.com?tags[]=flowers&category[]=garden
This does not work, if I change $value to $key then it will will, but it will remove all keys of the same type, not the behaviour I would like.
I activate this behaviour via a call in the blade template, this forms a href
//Pass through parameter type and parameter value
{{remove_query_params(['category' => $category->id]) }}
Has anybody got any pointers as to where I go next?#
Thanks and fingers crossed I am not far off :)
Adam
I hope this solution will help you:
<?php
function remove_query_params(array $params = [])
{
//Set to array
$existingParams = [
'tags' => [
'aaaa',
'bbbb'
],
'category' => 'ccc'
];
// go trough all parameters
foreach ($existingParams as $key1 => $value1) {
// go to the parameters, which need to be deleted
foreach ($params as $key2 => $value2) {
// only if the keys equals, do something
if ($key1 === $key2) {
// if the param is an array
if (is_array($value1)) {
foreach ($value1 as $k => $v) {
// if the elements to delete are an array
if (is_array($value2)) {
foreach ($value2 as $b => $r) {
if ($v == $r) {
unset($existingParams[$key1][$k]);
}
}
} else {
if ($v == $value2) {
unset($existingParams[$key1][$k]);
}
}
}
} else {
if (isset($existingParams[$key2])) {
unset($existingParams[$key2]);
}
}
}
}
}
$query = http_build_query($existingParams);
return $query;
}
echo remove_query_params(['tags' => 'aaaa']);
echo "\n";
echo remove_query_params(['tags' => ['aaaa', 'bbbb']]);
echo "\n";
echo remove_query_params(['category' => 'ccc']);
echo "\n";
tags is not an associated array. It is just a list of strings. Also, look at the value of $existingParams = request()->query(); It is not the tags array. It is an object that contains it. That is why when you use $key it works but deletes everything because $key is tags. So, in your check $existingParams['tags'] should be checked for the shrubs value. in_array is what you are looking in this case.
Hope this will solve your problem.I just provided the core function to get the things done in a way
$query = "tags[]=flowers&tags[]=shrubs&category[]=garden";
echo (remove_query_params( [ 'tags' => 'shrubs' ], $query ));
function remove_query_params(array $params = [], $query )
{
parse_str( $query, $existingParams );
$existing_keys = array_keys( $existingParams);
foreach($params as $key=>$value){
if( in_array( $key, $existing_keys ) ){
foreach ($existingParams[$key] as $param_key => $param_value) {
if( $param_value == $value ){
unset( $existingParams[$key][$param_key] );
}
}
}
}
$query = http_build_query($existingParams);
return $query;
}

Change the index of an array

I need help to change the index of an array.
I have this array:
$items = array('items' => array(
0 => array(
'item_id' => 1,
'item_amount' => 100,
),
1 => array(),
));
Now I want to remove the index, based on the value of item_id, but I don't know how to do this.
I've tried to do it as follows, but doesn't work.
foreach($items['items'] as $key) {
$removeIndex = $key['item_id'] == 1;
if($removeIndex) {
unset($removeIndex);
}
}
How can I do this?
You need to use unset like this:
foreach($items['items'] as $index => $key) { // also get the index!
if (!isset($key['item_id'])) continue; // skip
$removeIndex = $key['item_id'] == 1;
if($removeIndex) {
unset($items['items'][$index]['item_id']); // specify path to that entry
}
}
See it run on eval.in.
To unset something in your nested array structure, you need to act on that array itself. unset($removeIndex) does not change the array, because that is a boolean value.
The extra if is there for the case when you don't have an item_id in some sub-array: in that case that iteration of the loop is skipped.
Removing the entire "row"
If your aim is to also remove the sub-array to which the item_id belongs (so including the item_amount and any other value in that sub-array), then just shorten the "path" in the unset statement:
foreach($items['items'] as $index => $key) { // also get the index!
if (!isset($key['item_id'])) continue; // skip
$removeIndex = $key['item_id'] == 1;
if($removeIndex) {
unset($items['items'][$index]); // specify path to that entry
}
}
See it run on eval.in.
You need to call unset($items['items'][0]). For your case it will be something like this:
$id = 1;
$keyToRemove = false;
foreach ($items['items'] as $key => $value) {
if ($value['item_id'] == $id) {
$keyToRemove = $key;
break;
};
}
if ($keyToRemove) {
unset($items['items'][$keyToRemove]);
}
If you want to remove the specific entry 'item_id' in the $items array, you have to refer to it and use both keys, like in:
foreach($items['items'] as $key => $val) {
if (!isset($val['item_id'])) continue;
$removeIndex = $val['item_id'] == 1;
if($removeIndex)
unset($items['items'][$key]);
}
If you downvote, please state why you think this answer is not appropriate.

two foreach loop on if statement

Wondering if it's possible to have a foreach loop call on if statement like this :
if (class_exists('WooCommerce')) {
foreach (array_combine($val1, $val2) as $key => $row_values)
}
else {
foreach ( $val1 as $key => $row_values )
}
{ begin of loop code
What I'm trying to do is to have a foreach loop if woocommerce plugin is active and to have another foreach loop if woocommerce isn't active.
This is not possible the way you try it, since that is invalid syntax.
What you can do is something like that:
<?php
$iterationArray = class_exists('WooCommerce') ? array_combine($val1, $val2) : $val1;
foreach ($iterationArray as $key => $row_values) {
// begin of loop code
} // end loop
What you need to do if a condition before the loop to assign the variables you will use to loop, just like this:
if ( class_exists( 'WooCommerce' ) ) {
$newVal = array_combine($val1, $val2);
} else {
$newVal = $val1;
}
foreach ( $newVal as $key => $row_values ) {
// do stuff
}
The result will be the same as what you were trying to do. But the syntax you proposed in your question is not supported in PHP, and can be worked around with the way proposed above.

How to Convert Nested array to Value in PHP?

My arrays
a:3:{s:6:"Choice";a:2:{i:0;s:5:"First";i:1;s:6:"Second";}s:5:"fcode";s:26:"form_rajas_exmsw2rpc81anlj";s:9:"useremail";s:26:"rajasekarang.cud#gmail.com";}
array (
'Choice' =>
array (
0 => 'First',
1 => 'Second',
),
'fcode' => 'form_rajas_exmsw2rpc81anlj',
'useremail' => 'rajasekarang.cud#gmail.com',
)
my php code
$arrays = 'a:3:{s:6:"Choice";a:2:{i:0;s:5:"First";i:1;s:6:"Second";}s:5:"fcode";s:26:"form_rajas_exmsw2rpc81anlj";s:9:"useremail";s:26:"rajasekarang.cud#gmail.com";}';
$decode = unserialize($arrays);
foreach($decode as $key => $value) {
echo '<td width="100">' . $value . '</td>';
}
My Error is :
Notice: Array to string conversion in....
The first Values in Nested Array.
How to convert nested array as a Value?
I need to show like this,
<tr><td>First,Second</td><td>form_rajas_exmsw2rpc81anlj</td><td>rajasekarang.cud#gmail.com</td></tr>
If $value is an array, you need a nested loop.
foreach ($decode as $key => $value) {
if (!is_array($value)) {
$value = array($valule);
}
foreach ($value as $subvalue) {
echo "<td width='100'>$subvalue</td>";
}
}
If you can have multiple levels of nesting, you should write a recursive function that handles each level.
If you want a sub-array to be shown as a comma-separated list, you can use implode.
foreach ($decode as $key => $value) {
if (is_array($value)) {
$value = implode(', ', $value);
}
echo "<td width='100'>$subvalue</td>";
}
you have nested array populated with elements of diferent size so you will always get an error. so in your foreach loop, you can check if the value is an array or not, like for instance
if (count($value)>1){
//code here like for instance echo $value[0]...
}//not recomended becuse an array can have only one value, but you can if you know you will put at least 2
or
if(is_array($value)..
Me I will do the following:
foreach($thing as $thingy =>$that){
//check if array or not
if(is_array($that)){
foreach($that as $t)
//do whatever
}else
//do whatever
}

Getting certain array from a multidimensional array

I have multidimensional array which is a query returning the info from a table named 'users'. In another part of my code I need to get the records of only one certain user and I want to take it using the array I mentioned above. It's of type:
This is probably what you're looking for:
$row = NULL;
foreach ($parent as $key => $child)
{
if (1 == $child['id'])
{
$row = $child; break;
}
}
if (isset($row))
{
// Stuff to do with the chosen row
}
$main = // your array
foreach ($main as $index => $sub) {
foreach ($sub as $subIndex => $item) {
if ($item['id'] == xxx) {
return $main[$index][$subIndex];
}
}
}
IMO using for loops (rather that foreach) would make it easier for you to reference the variable you need (by using the for loop variable to look up the appropriate row in the array)
HTH,
David

Categories