Turn a string into an array using PHP - php

My session variables are
$_SESSION["listofIds"]=163,164;
$_SESSION["listofVals"]=4,3;
I want to select session values like
$_SESSION["listofIds"][0]=163;
$_SESSION["listofIds"][1]=164;
$_SESSION["listofVals"][0]=4;
$_SESSION["listofVals"][1]=3;
I tried
echo $_SESSION["listofIds"][0];
then it prints '1' i.e. first character. How can I handle this?
Also how can I get 1st element of $_SESSION["listofIds"] and 1st element of $_SESSION["listofVals"] after placing in while loop for mysql query.

Your session variables seem to be strings. Use
$IdsArr = explode(",", $_SESSION["listofIds"]);
echo $IdsArr[0];
With explode splitting the string by "," to an array.

$listofIds = array();
$listofIds = explode(",",$_SESSION["listofIds"]);
now you can access the variables using listofIds[0] or listofIds[1].

First of all you should start by defining from scratch an array while placing values in the $_SESSION array. This is a better way to write code.
Anyway as all the other answers said:
$listofIds = array();
$listofIds = explode(",",$_SESSION["listofIds"]);
will convert your string into an array and you will be able to access each value in different ways. Most commons:
using a foreach loop
getting the index of the item you want to use.
If you want to use the first item in a query you should get its value using the index (array starts from 0) so your value will be $listofids[0]. The same logic will apply to the other $_SESSION value.
Another good practice for programming: when you put an array value in a query string assign it to a variable before:
$id_to_search = $listofids[0];
and then use it into the query:
$sql = "SELECT * FROM your_table WHERE id='$id'";
This will save you a lot of headache with singe and double quotes.

Related

PHP JSON Arrays within an Array

I have a script that loops through and retrieves some specified values and adds them to a php array. I then have it return the value to this script:
//Returns the php array to loop through
$test_list= $db->DatabaseRequest($testing);
//Loops through the $test_list array and retrieves a row for each value
foreach ($test_list as $id => $test) {
$getList = $db->getTest($test['id']);
$id_export[] = $getList ;
}
print(json_encode($id_export));
This returns a JSON value of:
[[{"id":1,"amount":2,"type":"0"}], [{"id":2,"amount":25,"type":"0"}]]
This is causing problems when I try to parse the data onto my android App. The result needs to be something like this:
[{"id":1,"amount":2,"type":"0"}, {"id":2,"amount":25,"type":"0"}]
I realize that the loop is adding the array into another array. My question is how can I loop through a php array and put or keep all of those values into an array and output them in the JSON format above?
of course I think $getList contains an array you database's columns,
use
$id_export[] = $getList[0]
Maybe can do some checks to verify if your $getList array is effectively 1 size
$db->getTest() seems to be returning an array of a single object, maybe more, which you are then adding to a new array. Try one of the following:
If there will only ever be one row, just get the 0 index (the simplest):
$id_export[] = $db->getTest($test['id'])[0];
Or get the current array item:
$getList = $db->getTest($test['id']);
$id_export[] = current($getList); //optionally reset()
If there may be more than one row, merge them (probably a better and safer idea regardless):
$getList = $db->getTest($test['id']);
$id_export = array_merge((array)$id_export, $getList);

Serialized multidimensional stored in MySQLi does not print past first array

Confusing title, the basics are that I'm saving a fully sorted and ordered multidimensional array from a script and into MySQL. I then, on another page, pull it from the database and unserialize it, and then proceed to print it out with this,
$s = "SELECT * FROM gator_historical_data WHERE channelid = '{$chanid}'";
$r = $link->query($s);
$comboarray = array();
while ($row = mysqli_fetch_assoc($r)) {
$comboarray[] = unserialize($row['dataarray']);
}
foreach ($comboarray as $item) {
$desc = $item['content']['description'];
$title = $item['content']['title'];
$datetime = $item['datetime'];
// ... ^^^ problems getting array data
}
The problem is that it doesn't take the full array from MySQL, only the first entry and thus only prints the first 'array'. So where the returned value from dataarray looks like this (var_dump): http://pastebin.com/raw.php?i=Z0jy55sM the data stored into the unserialized $comboarray only looks like this (var_dump): http://pastebin.com/raw.php?i=Ycwwa924
TL;DR: Pulling a serialized multidimensional array from a database, unserializing and it loses all arrays after the first one.
Any ideas what to do?
The string you've got is a serialized string plus something more at the end that is also a serialized string again and again:
a:3:{s:6:"source";s:25:"World news | The Guardian";s:8:"datetime ...
... story01.htm";}}a:3:{s:6:"source";s:16:"BBC News - World";
^^^
This format is not supported by PHP unserialize, it will only unserialize the first chunk and drop everything at the end.
Instead create one array, serialize it and store that result into the database.
Alternatively you can try to recover for the moment by un-chunking the string, however in case the paste was done right, there are more issues. But on the other hand the paste obvious isn't the done fully correct.

Adding key-value in PHP array?

Inside a loop where I'm dealing with variables related to a product and a number of units, I'm trying to add these two to an array:
$pedido = array();
So,
foreach($_POST as $post_key => $post_value){
if ($post_value=="on") {
$nombreProducto = mysql_fetch_assoc($mySQL->query("SELECT nombre from productos WHERE id_producto='$post_key'"));
$cantidad = $_POST[$post_key."Number"];
echo "<h1>".$nombreProducto['nombre']."</h1>"." Cantidad: ".$cantidad." <br><br>";
$pedido["$nombreProducto"] = $cantidad;
}
}
It's right in:
$pedido["$nombreProducto"] = $cantidad;
Where I try to perform the adding, however the output of var_dump is like:
array(1) { ["Array"]=> string(1) "3" }
Not exactly what I wanted neither the format.
Use $pedido[$nombreProducto['nombre']] = $cantidad; instead of $pedido["$nombreProducto"] = $cantidad;
Remove quotes and
$pedido[$nombreProducto['nombre']] = $cantidad;
EDITED
It seems $nombreProducto is an array so you need to indicate the key field, so i changed to use the field "nombre"
If you see your var_dump it's an Array with the key "Array" this is why you are trying to convert the array to string and it return the word "Array"
You shouldn't be putting a variable by itself in quotes. Remove the quotes.
Also, since you were just accessing $nombreProducto['nombre'] on the previous line, it's fairly obvious that that variable is an array. You cannot use an array as a key, only integers and strings are allowed. So use something that identifies it, such as its ID number.
The following makes no sense to do:
$pedido["$nombreProducto"] = $cantidad;
What are you trying to do here? I think what you want to do is this:
$pedido[$nombreProducto['nombre']] = $cantidad;
Also you may want to try to output the array like this:
print_r($pedido);
I recommend you re-write the mysql query so you don't need to loop it. That is for safety and efficiency reasons. I also recommend you use mysqli instead of mysql, because mysql is deprecated and unsafe to use. You don't check if $_POST[$post_key."Number"] is set, at least not in this code. I hope you sanitize/validate the input from $_POST before using it against the database?

Implode variables in PHP

I'm trying to implode variables, but it's not working correctly:
$models = array("$model0, $model1");
$modelfinal = implode("," , $models);
$modelfinal only returns , ,
I'm guessing I'm way off...anybody?
The following statement creates an array with exactly one string in it, which is comprised of the values of two (apparently) undefined variables separated with a comma:
$models = array("$model0, $model1");
The end result is the same as if you had done this:
$models = array(", ");
Now you're imploding it using a comma as the separator, which doesn't do anything since there's only one element in the array (a string with a comma and a space).
Assuming $model0 and $model1 are defined (which is a problem you'll need to look into first), you can get your desired result either by:
directly using $modelfinal = "$model0, $model1",
or by using $models = array($model0, $model1); followed by the implode.
here is your problem "$model0, $model1" change it to this code
$models = array($model0,$model1);

how to save numbers only from an array into a new array

I currently have var: $_REQUEST['fb_friend_uid'] which gives me the following output:
Array{"returned_val":["47483647","47483647","47483647","665414807","263901486","665414807","665414807","665414807"]}
Im looking to save the data here into a new array, containing only the numbers in a format of; 47483647, 47483647, etc
The objective is to use it in a sql query like so:
SELECT * FROM vote WHERE
vote_fb_uid IN ($myNumbers)
Saving it into a new array I figured could be done like so:
foreach ($_REQUEST['fb_friend_uid'] as $uid) {
$uids[] = $uid['id'];
}
$ids = join(',', $uids);
However my issue remains, how to "clean" the first var to contain numbers only.
Suggestions?
I can't give you an exact solution, because I'm not sure if the value returned by $_REQUEST['fb_friend_uid'] is a PHP array printed using json_encode(), or the value is actually a json string.
In either case, where is an example which makes use of both circumstances, so use whichever one makes sense in your scenario:
If PHP Array:
Assumes PHP Array has a format similar to:
array('returned_val' => array('47483647', '47483647', '47483647', '665414807', '263901486', '665414807', '665414807', '665414807'));
<?php
$original_arr = $_REQUEST['fb_friend_uid']['returned_val'];
If JSON String:
Assumes the JSON String has a format similar to:
{"returned_val":["47483647","47483647","47483647","665414807","263901486","665414807","665414807","665414807"]}
<?php
$json_arr = json_decode($_REQUEST['fb_friend_uid'], True);
$original_arr = $json_arr['returned_val'];
Then, use this code:
<?php
// Extract only whole number values, omit anything which is not a 0-9 character.
$filtered_arr = array_filter($original_arr, 'ctype_digit');
// Escape values to remove possibility of SQL injection.
$filtered_arr = array_map('mysql_real_escape_string', $filtered_arr);
// Convert the array to a string
$string_arr = "'" . implode("','", $filtered_arr) . "'";
// Perform SQL Query
mysql_query("SELECT * FROM vote WHERE vote_fb_uid IN ($string_arr)");
Just filter the array using is_numeric:
$uids = array_filter($_REQUEST['fb_friend_uid'], 'is_numeric');
To filter for numbers you can use is_numeric( mixed $var ).
But if you need more control (only integers of certain type, length) you can either use REGEX or is_numeric and some ifs.
This looks like a json string, so use http://php.net/json_decode
Maybe you need to remove Array at the beginning (but I don't know if Array is actual in the variable), use http://php.net/substr
$jsonString = substr($_REQUEST['fb_friend_uid'], 5);
$fb_friend_uid = json_decode($jsonString);
$ids = join(',', $fb_friend_uid['returned_val']);

Categories