how to put an array item to the end in php? - php

how to put an array item to the end in php?
I want to put some item of array to the last position , when I loop and output the $arr to html, this will keep the 'other' item always at the end. what is the best and easy way to do it?
<?php
$arr=array(
'a'=>'hello',
'game'=>'boy',
'other'=>'good',
'name'=>'jimmy',
//...
);
// how to resort $arr to put other item to then end of $arr
$arr=array(
'a'=>'hello',
'game'=>'boy',
'name'=>'jimmy',
//...
'other'=>'good'
);
?>

with the example you have given ksort($arr) would sort it alphabetically and put the other item to the end.
second option is to remove the other item from the array using array_slice and then placed it in the back using array_merge

Assuming you're not simply asking to sort the array based on the alphabetical property of the keys, given your array:
$arr=array(
'a'=>'hello',
'game'=>'boy',
'other'=>'good',
'name'=>'jimmy',
);
You have to take the old key out first, while saving its value:
$old = $arr['other'];
unset($arr['other']);
Then, append it to the array like this:
$arr += array('other' => $old);

First store all the element that you required.
Like
$arr=array(
'a'=>'hello',
'game'=>'boy',
'name'=>'jimmy');
After that add
$arr['other']='good';
Now other element is always at last.....

Related

Restructure 2d array so that column values become row values (transpose but preserve first level keys)

The situation is as follows. I have a parent array which looks like the following:
$parent = [
1 => ['test1', 'test2'],
2 => ['test1_1', 'test2_2'],
];
I would like to group the data by column.
Desired result:
[
1 => ['test1', 'test1_1'],
2 => ['test2', 'test2_2'],
]
1 parent array called parent contains 2 arrays inside. I want to combine these two so that they have the same values as stated above. So this would mean that the arrays should be combined based on index number.
Since I do not make use of string keys, how would I accomplish this? I believe that there is no build in function available for this situation.
I would imagine that I could start beginning to create a new array and use a for loop through the parent array.
I tried the array-combine function however, this is NOT displaying the results I want.
[
1 => ['test1' => 'test1_1', 'test2' => 'test2_2'
]
If you need to preserve those first level keys, you can re-apply them after tranposing.
Code: (Demo)
var_export(
array_combine(array_keys($parent), array_map(null, ...$parent))
);
Otherwise, you can just transpose and accept the re-indexed first level keys. Honestly, I can't see any good reason to preserve the first level keys because by transposing, you remove the initial association between first level keys and the row values.
Code: (Demo)
var_export(
array_map(null, ...$parent)
);
If these techniques do not suit your actual project data, then we will need a more realistic sample array to be provided in your question body.
Loop over the keys of the top-level array. Then use the current index of the iteration to get the corresponding columns of the nested arrays.
$result = [];
foreach (array_keys($parent) as $i => $k) {
$result[$k] = array_column($parent, $i);
}
DEMO
This assumes the number of rows is the same as the number of columns. It's not clear what you expect the result to be if that's not true.

Wordpress output to array in query from custom field

I have created a custom field named "sec1array" in my categories so that i can add an array, for example 1,2,3,4
I want to retrieve that array and output it in the loop, so I created this code.
$seconearray = array($cat_data['sec1array']);
$args = array(
'post__in' => $seconearray
);
However, it only seems to be outputting the first post in the array. Is it something to do with the way the comma is outputting?
If I print $seconearray it outputs correctly, example 1,2,3,4
What you are doing is storing a string value of "1,2,3,4" in your database which when you are trying to construct an array from it like array("1,2,3,4") you end up just assigning a single value to that new array. This is why it only contains a single value.
You need to store your value in a serializable format so it can be converted back to an array after you save it to the database. There are many ways to do this, I'm sure others will give more examples:
JSON encode it
json_encode(array(1,2,3,4)); // store this in your db
json_decode($cat_data['sec1array']); // outputs an array
Or, you can use PHP serialize
serialize(array(1,2,3,4)); // store this in your db
unserialize($cat_data['sec1array']); // outputs an array
If you want to keep your string, you can explode it:
explode(',', $cat_data['sec1array']); // outputs your array of 1,2,3,4.
Using any of these methods will work. Finally you'll end up with an example like:
$seconearray = explode(',', $cat_data['sec1array']);
$args = array(
'post__in' => $seconearray
);

Delete one item from array with matching keys

I have an array
$array = ['f'=>'foo', 'f'=>'foo', 'f'=>'foo','g'=>'good'];
and I want to delete only one item from this array with matching key, like the following:
unset($array['f']);
However, this will delete the all items with this matching key 'f' and only one item will remain. Is there a way to do something like this, but apply it only to the first matching item in the array?
First of all you have a syntax error.
$array=$array(['f'=>'foo', 'f'=>'foo', 'f'=>'foo','g'=>'good']);
You have an $ extra and [] extras, and you can't have a lots off records with the same key(because the last one will override the previously)... The correct way to define
$array= array('f'=> array('foo', 'foo2', 'foo3'), 'g'=>'good');
The values will be a new array inside de F key. And then you can remove only one record
unset($array['f'][0]);
now your arrays var_dump:
$array= array('f'=> array('foo2', 'foo3'), 'g'=>'good');
i have solved this by using this as per cmorrissy comment there will be only one item so that variable was showing me qty, i have to check if
if($product[$id]['quantity']>1){ $product[$id]['quantity']--;}else{unset($product[$id]);}
if you var_dump($array); this would be the output
var_dump($array);
array(
f => foo
g => good
)
since you have an array with the same index it will be displayed as one, and thats why it will be deleted

Array item call

I have problem with calling Array which are form redux framework to wordpress
when i execute this:
print_r ($ka_opt['theme-order']);
i have this result:
Array ( [nr2] => 1 [nr3] => 1 [nr1] => 1 )
I need to call specific item from this array for example first item, i tryed this to call first possition but dont work:
echo $ka_opt['theme-order'][0];
whats wrong? i dont know how to call variable
That is an associative array, not a numerically keyed array. You can't use numerical keys with associative arrays. You must use their proper keys:
echo $ka_opt['theme-order']['nr2'];
If you want the first item you can us array_shift():
echo array_shift($ka_opt['theme-order']);
If you want a deeper array element you can use array_slice():
// get second element, assuming PHP5.4+
echo array_slice(array_values($ka_opt['theme-order']), 1, 1)[0];
And, of course, you can always loop through it to get the values you seek.

PHP: Session 2-Dimensional Array - Track Viewed Products

I'm trying to create an array to display the last 5 products a customer has viewed.
The array is a 2 dimensional array like below...
$RView= array(
array( ID => "1001", RefCode => "Ref_01", Name => "Name_01" ),
...
array( ID => "1005", RefCode => "Ref_05", Name => "Name_05" )
);
The array values are retrieved from the products recordset and is designed to function as follows when a customer visits a product page.
Page will check if a Session Array exists
If yes, an array variable is created from existing Session
If no, a new array is created.
Array will add the new product details.
Array will count if there are more than 5 existing products in the array.
If yes, it will remove the oldest.
If no, moves to next step.
A Session is created/updated from the revised Array.
My current effort is attached below...
Many thanks for any help.
<?php
session_start()
// Get or Create Array
IF (isset($_SESSION['sessRView'])) {
$RView = ($_SESSION['sessRView']); }
ELSE {
$RView = array(array());
}
// Append currently viewed Product to Array
array(array_unshift($RView, $row_rsPrd['PrdID'], $row_rsPrd['RefCode'], $row_rsPrd['Name']));
// Check if more than 5 products exist in Array, if so delete.
IF (sizeof($RView) > 5) {
array(array_pop($RView)); }
// Update Session for next page
$_SESSION['sessRView'] = $RView;
// Display Array
for ($row = 0; $row < 5; $row++)
{
echo "<ul>";
echo "<li><a href='?PrdID=".$RView[$row]["PrdID"]."'>".$RView[$row]["RefCode"]."</a> : ".$RView[$row]["Name"]."</li>";
echo "</ul>";
}
?>
It's more or less right - just 2 lines need to be changed.
There's no need for the extra array() around array_unshift and array_pop.
When you use array_unshift you're pushing an array of items (not the id/codes individually) - I think you mean array_unshift($RView, array($prodid,$name,...))
What if $RView doesn't have 5 elements? In that case you're accessing undefined array indices (which may or may not show an error). Change it to a foreach loop: e.g.
foreach ($Rview as $prod) echo $prod['Name']...
It should work after you make these changes. You might want to clean up the coding style a bit, though :)
EDIT: Oh, I see, when you're referencing the array in the for loop it doesn't know that the array has "ProdID" and "Name" indices. When you make an array you have to define the indexes using the => operator.
Add indexes to the array when you array_unshift:
array_unshift($RView, array("ProdID" => $row_rsProd["ProdID"], "Name"...))
If row_rsProd isn't too big, you can just tack the entire row_rsprod onto $RView.
so change array_unshift(...) to just $RView[] = $row_rsProd
This way the indexes are preserved.
Alternatively you can change the indicies in the for loop to match. Right now the array you unshift onto $RView is 0-based - $RView[0][0] is the product ID for the first product, etc.
So you can change the stuff in the foreach loop to
echo "<li>..." $prod[0] $prod[1] $prod[2]
Hope that helps!

Categories