Create nested arrays from specific variables within session - php

I have several values stored in $_SESSION beginning with 'first_name_' & 'last_name_' which then a number appended to the end deepening on how many names are generated.
I am able to extract each of these values from the session and add to an array but would like to pair up the first and last names together within a nested array. (if that makes sense)
at the moment I have:
$users_array = array();
foreach ($_SESSION as $key => $value) {
if(strpos($key, 'first_name_') === 0) {
$users_array[] = $value;
}
if(strpos($key, 'last_name_') === 0) {
$users_array[] = $value;
}
}
This produces an output with var_dump:
array
0 => string 'John' (length=4)
1 => string 'Smith' (length=8)
2 => string 'Jane' (length=4)
3 => string 'Doe' (length=3)
But what I would like is something like:
array
'user' =>
array
'first_name' => string 'John' (length=4)
'last_name' => string 'Smith' (length=5)
array
'first_name' => string 'Jane' (length=4)
'last_name' => string 'Doe' (length=5)
Any suggestions on how I can achieve this?

deceze is right in his comment... But just so people with similar issues with creating 2-dimensional array from a 1-dimensional array, here is a solution. Also, note that PHP does not guarantee that the order will be same when iterating using FOREACH. As this will work, it is still prone to errors.
$users_array = array();
foreach ($_SESSION as $key => $value) {
if(strpos($key, 'first_name_') === 0) {
$users_array[] = array();
$users_array[count($users_array)-1]['first_name'] = $value;
}
if(strpos($key, 'last_name_') === 0) {
$users_array[count($users_array)-1]['last_name'] = $value;
}
}

Related

Check that variable is in an array

Possibly already been asked but I can't seem to find the answer I'm looking for.
How can I check that a variable is in an array?
Here is my code so far - ideally I wan't to echo out something when the ProductID also exists in the lastUpdatedProduct array as well as the productOptions array.
<?php if ($this->productOptions) { ?>
<?php foreach ($this->productOptions as $options) {
$array = $this->lastUpdatedProduct;
echo '<strong>' . $options['ProductID'] . '</strong>';
if(in_array($options['CentreID'], $array)) {
echo 'it exists';
}
}
}?>
Heres my array:
array
0 =>
array
'pid' => string '391' (length=3)
1 =>
array
'pid' => string '467' (length=3)
2 =>
array
'pid' => string '474' (length=3)
3 =>
array
'pid' => string '2985' (length=4)
4 =>
array
'pid' => string '2985' (length=4)
5 =>
array
'pid' => string '424' (length=3)
The problem is that $array is an array with arrays and you are trying to find something inside one of the inner arrays. Try with this:
foreach ($array as $entry) {
if (is_array($entry) && in_array($options['CentreID'], $entry))
echo 'it exists';
}
Ideally I wan't to echo out something when the ProductID is in the array
if(is_array($options['ProductID'])) { }
Live Preview
Edit
Ideally I wan't to echo out something when the ProductID also exists in the lastUpdatedProduct array as well as the productOptions array.
if(is_array($this->productOptions)) {
foreach($array as $pid) {
if(in_array($pid, $options['ProductID'])) {
//echo
}
}
}

Elements combination of same array in PHP

In my project, i will have to receive a string from user (in textarea). Now this string will be converted into array. Now the problem is that, the character length must be minimum of 3,
in the following array next element should be joined to current one if character length is less than 3. How to perform it in PHP.
a[0]=>this a[1]=>is a[2]=>an a[3]=>example a[4]=>array.
Output should be:
a[0]=>this a[1]=>isan a[2]=>example a[3]=>array.
Just try with:
$input = ['this', 'is', 'an', 'example', 'array.'];
$output = [];
$part = '';
foreach ($input as $value) {
$part .= $value;
if (strlen($part) > 3) {
$output[] = $part;
$part = '';
}
}
Output:
array (size=4)
0 => string 'this' (length=4)
1 => string 'isan' (length=4)
2 => string 'example' (length=7)
3 => string 'array.' (length=6)

urldecode losses 1 parameter

I'm using urlencode & urldecode to pass variables trough a html-form.
$info = 'tempId='.$rows['tempID'].'&tempType='.$rows['tempType'].'&dbId='.$rows['ID'];
echo '<input type="hidden" name="rank[]" value="'.urlencode($info).'" >';
Here is what is in $rows
array (size=4)
'ID' => string '110' (length=3)
'tempID' => string '1' (length=1)
'tempType' => string 'temp_first' (length=10)
'pageOrder' => string '0' (length=1)
So $info is
tempId=1&tempType=temp_first&dbId=110
But if i then decode it, it losses 1 parameter. How is this possible?
foreach (explode('&', urldecode($list[$i])) as $chunk) {
$param = explode("=", $chunk);
$tempId = urldecode($param[0]); // template id
$tempType = urldecode($param[1]); // Template type
$dbId = urldecode($param[2]); // database ID
var_dump($param);
}
Output:
array (size=2)
0 => string 'dbId' (length=4)
1 => string '110' (length=3)
Sometime there are even things in the array wich should not be in there, for example instead of temp_first it says tempType. Just the variable name.
I hope you guys can help me
There's no need to explode and process the string manually, you can use parse_str():
parse_str(urldecode($list[$i]), $output);
var_dump($output);
Would output:
array
'tempId' => string '1' (length=1)
'tempType' => string 'temp_first' (length=10)
'dbId' => string '110' (length=3)
try this
$result=array();
foreach (explode('&', urldecode($list[$i])) as $chunk) {
$param = explode("=", $chunk);
$result[$param[0]]=$param[1];
}
var_dump($result);
Could you try this and check the result (I'm groping in the dark though):
//change this <input type="hidden" name="rank[]" value="'.urlencode($info).'" > to
//<input type="hidden" name="urlargs" value="'.urlencode($info).'" >
$values = explode('&',urldecode($_POST['urlargs']));
$arguments = array();
foreach($values as $argument_set){
$data = explode('=',$argument_set);
$arguments[$data[0]] = $data[1];
}
var_dump($arguments);
I believe the problem is in the way you're processing the value
$data=array();
foreach (explode('&', urldecode($list[$i])) as $chunk) {
$param = explode("=", $chunk); //
$data[$param[0]]=$param[1]
}
Instead of grouping all code together, start by putting it in seperate vars and echo the content for debugging. Because you are saying you loose one variable, but the output you show is just one of the variables. What is the var_dump of the other two?
Because your var_dump($param); would output the part before the '=' and after the '=', so indeed i would expect the output to be something like: So which one of these are you missing?
array (size=2)
0 => string 'tempId' (length=6)
1 => string '1' (length=1)
array (size=2)
0 => string 'tempType' (length=8)
1 => string 'temp_first' (length=10)
array (size=2)
0 => string 'dbId' (length=4)
1 => string '110' (length=3)
DEBUG code:
foreach ($list as $row) {
echo 'Full row:: '. $row.'<br>';
//if the data is comming via GET or POST, its already decoded and no need to do it again
$split = explode('&', urldecode($row));
foreach($split as $chunk) {
echo 'Chunk:: '.$chunk.'<br>';
$param = explode('=', $chunk);
echo 'param name:: '.$param[0].'<br>';
echo 'param value:: '.$param[1].'<br>';
}
}

How to extract array data in PHP variable with foreach?

I need to extract last array data i.e SiteName, Url, Title to the variable in php.
array
'ApplicableProductOfferings' =>
array
0 => string 'EasyDemo' (length=10)
'Artist' => string 'Hello' (length=10)
'ReferralDestinations' =>
array
0 =>
array
'SiteName' => string 'gettyimages' (length=11)
'Url' => string 'http://www.gettyimages.com/detail/160414706' (length=43)
'Title' => string 'Pixie Lott Launches The New BlackBerry Z10' (length=42)
'UrlComp' => string 'http://localhost.com' (length=197)
'UrlPreview' => string 'http://localhost.com' (length=164)
'UrlThumb' => string 'http://localhost.com' (length=82)
'UrlWatermarkComp' => string 'http://localhost.com' (length=197)
'UrlWatermarkPreview' => string 'http://localhost.com
try this.......
foreach($data as $dat)
{
foreach($dat['ReferralDestinations'] as $key => $d)
{
echo $d['SiteName'];
echo $d['Url'];
echo $d['Title'];
}
}
It depends on how you are storing the data in the array. If you have an array that already has the last array data, it's very simple.
foreach ($myArray as $var) {
echo $var;
}
or access individual elements as $myArray['SiteName'], $myArray['Url'] etc..
Assuming you have the above data in an array of arrays called $arrayOfArrays
foreach ($arrayOfArrays as $myArray) {
// $myArray now holds first array, second array etc as the loop is executed
// First time it holds 'ApplicableProductOfferings', second time 'ReferralDesinations'..
// If the array is 'ReferralDesitnations' you can loop through that array
// to get the elements you are looking for SiteName etc as below
foreach ($myArray as $URLElement) {
echo $URLElement;
}
}
$array1 = [];
$array2 = [];
foreach ($array1 as $key=> $val) {
extract($array2, EXTR_IF_EXISTS, $val);
}
// extract() flags => EXTR_IF_EXISTS ...
// http://php.net/manual/ru/function.extract.php

Exploding string into array, but assigning first value of the string as key in new array

I'm trying to create an array, looping through another array and taking the string value within the key to assigning it as a key/value pair in the new array. Here's a sample of the array of values I'm using outputted via var_dump:
array
0 => string 'dog,bark' (length=8)
1 => string 'cat,meow' (length=8)
2 => string 'cow,moo' (length=7)
What I want to do have it so in the new array, it is set up as such
array
'dog' => string 'bark' (length=4)
'cat' => string 'meow' (length=4)
'cow' => string 'moo' (length=3)
I thought that explode would do the trick, delimiting by commas, but it doesn't populate the keys as intended, instead using the standard numerical values. So after doing some research and coming up blank, i'm wonder if there's a php function that i'm missing, or have missed some simple amount of logic that would do what i'm after.
EDIT: Forgot the most important part. Here's the current code that is assigning values to the new array. One reason not to code at 2am
foreach ($array as $key=>$value) {
$newArray= explode(',', $array [$key]);
}
$start = array('a,x', 'b,y', 'c,z');
$result = array();
foreach($start as $startVal){
list($key,$val) = explode(',', $startVal);
$result[$key] = $val;
}
$newArray = array();
foreach($array as $joined) {
list($key, $value) = explode(',', $joined);
$newArray[$key] = $value;
}

Categories