Multidimensional session array in PHP - php

I want to create a multidimensional session array in PHP.
$_SESSION['basket'][$id] = $array
$array refers to an array.
When I run this for a new $id, it is overwriting the previous entry in the $_SESSION['basket'].
Means every time count($SESSION['basket']) is 1.
Actually, i want to achieve following structure.
$_SESSION['basket'] = array($id1 => array(), $id2 => array(), .....)
EDITED:
if(!isset($_SESSION['basket'])) {
$_SESSION['basket'] = array();
$_SESSION['basket'][$id] = $array;
}
else{
$_SESSION['basket'][$id] = $array;
}
when i do
$_SESSION['basket'][$id] = implode('/',$array);
it works. but not working for another array as value.
How can i do this?
thanks.

I am providing the answer for my question. It may help some other people who have same issue.
do not store any objects in $_SESSION varibles. I was storing
$array = array( $key=>object($value),....)
Therefore, I cast object to string
$array = array($key => (string)$value, ...)
and it works.
hope it will help someone.

Use it like this:
$tmp = $_SESSION['basket'];
$tmp[$id] = array();
$tmp[$id] = $array;
That'll work.

Related

PHP $_POST array

I'm building a webhook that will receive data from an external service.
In order to retrieve data, I'm using the following array:
$data = [
$_POST['aaa'],
$_POST['bbb'],
$_POST['ccc'],
$_POST['ddd'],
$_POST['eee']
];
Is it possible to build the same array without repeating $_POST? I mean something like:
$data = $_POST [
['aaa'],
['bbb'],
['ccc'],
['ddd'],
['eee']
];
Obviously, that code is wrong.
Thanks.
There's no shortcut like that. You could use array_map():
$data = array_map(function($key) {
return $_POST[$key];
}, ['aaa', 'bbb', 'ccc', ...]);
$data = $_POST
This will build your new $data array the same way as your GLOBAL $_POST array including the POST Key names and their assigned values.
Also checkout extract($_POST), as this will extract each key to its same name variable, which may be easier to then reference in your web-hook or any functions or procedural code you uses from then on. This essentially does this:
$aaa = $POST['aaa']
$bbb = $POST['bbb']
$ccc = $POST['ccc']
etc etc
https://www.php.net/manual/en/function.extract.php
The simplest way for me would be:
For getting all the values in the $_POST array
foreach($_POST as $value){
$data[] = $value;
}
For getting all the values and want to keep the key
foreach($_POST as $key=>$value){
$data[$key] = $value;
}
For getting a specific array of values from the array
foreach(['aaa','bbb','ccc','ddd','eee'] as $column){
$data[] = $_POST[$column];
}
Just a good idea to always escape variables ;)
$con = mysqli_connect('hostcleveranswer.com','USERyouearn','PWDanupv0Te','dropthemicDB')
foreach($_POST as $key => $value) {
$data[] = mysqli_escape_string($con,$value);
}
//i feel that was a good simple answer using tools without having to a learn a new function syntax

PHP Unify duplicate array

in my PHP code I have many array like this:
0 = ['attr_id':1,'name':'qty','value':'100'];
1 = ['attr_id':1,'name':'qty','value':'200'];
2 = ['attr_id':1,'name':'qty','value':'500'];
3 = ['attr_id':2,'name':'price','value':'10$'];
I want merge this array like this:
0 = ['attr_id':1,'name':'qty','value':['100','200','500']];
1 = ['attr_id':1,'name':'price','value':'10$'];
can you guys help me please?
thanks
This should be simpler. Build the result using the attr_id as the index and append the value:
foreach($array as $values) {
$result[$values['attr_id']]['value'][] = $values['value'];
$result[$values['attr_id']] = $result[$values['attr_id']] + $values;
}
If you need to reindex, just use array_values() on the $result.
This is one method where you loop through an array_column array of the id's and use key to insert values from values array.
$value = array_column($arr, 'value');
$id = array_column($arr, 'attr_id');
$res =[];
Foreach($id as $key => $i){
If(!isset($res[$i])) $res[$i] = ['attr_id' => $i, 'name'=>'qty', 'value' => []];
$res[$i]['value'][] = $value[$key];
}
Var_dump($res);
https://3v4l.org/VXI5E
As you see I use the id as key to keep track of the result array.
If you want to clear this, meaning reset the counting from 0, use array_values.
$res = array_values($res);
Edit: also the 10$ is inside an array in my answer, this makes it easier to use the array later in my opinion.
If you must save it as an string I can fix it, but it will probably be harder to use the array later with a mixed item.

php - Find array for which a key have a given value

I have an array of dictionnaries like:
$arr = array(
array(
'id' => '1',
'name' => 'machin',
),
array(
'id' => '2',
'name' => 'chouette',
),
);
How can I find the name of the array containing the id 2 (chouette) ?
Am I forced to reindex the array ?
Thank you all, aparently I'm forced to loop through the array (what I wanted to avoid), I thought that it were some lookup fonctions like Python. So I think I'll reindex with id.
Just find the index of array that contains the id you want to find.
SO has enough questions and answers on this topic available.
Assuming you have a big array with lots of data in your real application, it might be too slow (for your taste). In this case, you indeed need to modify the structure of your arrays, so you can look it up faster, e.g. by using the id as an index for the name (if you are only interested in the name).
As a for loop would be the best way to do this, I would suggest changing you array so that the id is the arrays index. For example:
$arr = array(
1 => 'machin',
2 => 'chouette',
);
This way you could just get the name for calling $arr[2]. No looping and keeping your program running in linear time.
$name;
foreach ($arr as $value){
if ( $value['id'] == 2 ){
$name = $value['name'];
break;
}
}
I would say that it might be very helpful to reindex the information. If the ID is unique try something like this:
$newarr = array();
for($i = 0;$i < count($arr);$i++){ $newarr[$arr[$i]['id']] = $arr[$i]['name']; }
The result would be:
$newarr = array('1'=>'machin','2'=>'chouette');
Then you can go trough the array with "foreach" like this:
foreach($newarr as $key => $value){
if($value == "machin"){
return $key;
}
}
But of course the same would work with your old array:
foreach($arr as $item){
if($item['name'] == "machin"){
return $item['id'];
}
}
It depends on what you are planning to do with the array ;-)
array_key_exist() is the function to check for keys. foreach will help you get down in the multidimensional array. This function will help you get the name element of an array and let you specify a different id value.
function findKey($bigArray, $idxVal) {
foreach($bigArray as $array) {
if(array_key_exists('id', $array) && $array['id'] == $idxVal) {
return $array['name'];
}
}
return false;
}
//Supply your array for $arr
print(findKey($arr, '2')); //"chouette"
It's a bit crude, but this would get you the name...
$name = false;
foreach($arr as $v) {
if($v['id'] == '2') {
$name = $v['name'];
break;
}
}
echo $name;
So no, you are not forced to reindex the array, but it would make things easier.

While script inside of an array

pretty straight forward question this - I am trying to create an array to store the Model and Cost values taken from my database table. I figured I could begin the array, then create a while loop, and then end the array, and smiles all around. I may be mistaken, or I may have blindly missed something in my code, but could you have a look?
$array = array(
while ($overall_cost = mysql_fetch_assoc($query_ocost)) {
$overall_cost["model"] => $overall_cost["cost"],
}
);
var_dump($array);
I think this is what you're looking for:
$array = array();
while ($overall_cost = mysql_fetch_assoc($query_ocost)) {
$array[$overall_cost["model"]] = $overall_cost["cost"];
}
var_dump($array);
You can't do it like this. You need to add to the array inside the while loop:
$array = array();
while ($overall_cost = mysql_fetch_assoc($query_ocost)) {
$array[$overall_cost["model"]] = $overall_cost["cost"];
}
var_dump($array);
would be one way of doing it.
EDITED to produce simple array.
I don't think that will work. Try something like:
$array = array();
while ($overall_cost = mysql_fetch_assoc($query_ocost)) {
$array[$overall_cost["model"]] = $overall_cost["cost"];
}
var_dump($array);

Make 1d Array from 1st member of each value in 2d Array | PHP

How can you do this? My code seen here doesn't work
for($i=0;i<count($cond);$i++){
$cond[$i] = $cond[$i][0];
}
It can be as simple as this:
$array = array_map('reset', $array);
There could be problems if the source array isn't numerically index. Try this instead:
$destinationArray = array();
for ($sourceArray as $key=>$value) {
$destinationArray[] = $value[0]; //you may want to use a different index than '0'
}
// Make sure you have your first array initialised here!
$array2 = array();
foreach ($array AS $item)
{
$array2[] = $item[0];
}
Assuming you want to have the same variable name afterwards, you can re-assign the new array back to the old one.
$array = $array2;
unset($array2); // Not needed, but helps with keeping memory down
Also, you might be able to, dependant on what is in the array, do something like.
$array = array_merge(array_values($array));
As previously stated, your code will not work properly in various situation.
Try to initialize your array with this values:
$cond = array(5=>array('4','3'),9=>array('3','4'));
A solution, to me better readable also is the following code:
//explain what to do to every single line of the 2d array
function reduceRowToFirstItem($x) { return $x[0]; }
// apply the trasnformation to the array
$a=array_map('reduceRowTofirstItem',$cond);
You can read the reference for array map for a thorough explanation.
You can opt also for a slight variation using array_walk (it operate on the array "in place"). Note that the function doesn't return a value and that his parameter is passed by reference.
function reduceToFirstItem(&$x) { $x=$x[0]; }
array_walk($cond, 'reduceToFirstItem');
That should work. Why does it not work? what error message do you get?
This is the code I would use:
$inArr;//This is the 2D array
$outArr = array();
for($i=0;$i<count($inArr);$i++){
$outArr[$i] = $inArr[$i][0];
}

Categories