I'm trying to get multiple arrays in a CodeIgniter session:
if ($this->session->has_userdata('products')){
$outerarray = array(
$array = array(
'id' => $id,
'quantity' => 1
));
array_push($outerarray, $this->session->userdata('products'));
$data['products'] = $outerarray;
$this->session->set_userdata($data);
} else {
$data['products'] = array(
'id' => $id,
'quantity' => 1
);
$this->session->set_userdata($data);
}
The else part works fine, but when there is already an array in the session it will put it like this in the session:
array(2) { [0]=> array(2) { ["id"]=> string(1) "7" ["quantity"]=> int(1) } [1]=> array(2) { ["id"]=> string(1) "1" ["quantity"]=> int(1) } }
what i really want to see is this:
array(2) { ["id"]=> string(1) "7" ["quantity"]=> int(1) } array(2) { ["id"]=> string(1) "1" ["quantity"]=> int(1) }
Is there a possibility to have only the content of the $outerarray in the session and not the whole $outerarray itself?
You have to do it this way:
$data = array('id' => 1, 'quantity' => 2);
if (isset($_SESSION['products'])) {
array_push($_SESSION['products'], $data);
}
else {
$_SESSION['products'] = array($data);
}
Related
Don't know this question is asked before or not, cannot find after lot of searching.
My array looks like this,
array(3) {
[0]=>
array(2) {
[0]=>
array(1) {
["userId"]=>
string(3) "421"
}
[1]=>
array(1) {
["userId"]=>
string(3) "329"
}
}
[1]=>
array(1) {
[0]=>
array(1) {
["userId"]=>
string(3) "329"
}
}
[4]=>
array(2) {
[0]=>
array(1) {
["userId"]=>
string(3) "329"
}
[1]=>
array(1) {
["userId"]=>
string(3) "421"
}
}
}
What I want is,
array(1) {
[0]=>
array(5) {
[0]=>
array(1) {
["userId"]=>
string(3) "421"
}
[1]=>
array(1) {
["userId"]=>
string(3) "329"
}
[2]=>
array(1) {
["userId"]=>
string(3) "329"
}
[3]=>
array(1) {
["userId"]=>
string(3) "329"
}
[4]=>
array(1) {
["userId"]=>
string(3) "421"
}
}
}
I have tried with array_merge, array_combine and a lot of foreach() loops. But didn't get luck for desired output.
Don't know how to do this. Please help.
You can flatten your array like this:
$arr = array(array(['user' => 1], ['user' => 2]), ['user' => 3]);
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
foreach($iterator as $val) {
$flattened_arr[0][] = $val;
}
var_dump($flattened_arr);
UPDATE: If you don't want to use RecursiveIteratorIterator, the you can also do it like this using array_walk_recursive():
$non_flat_arr = array(array(['user' => 1], ['user' => 2]), ['user' => 3]);
$objTmp = (object) array('flat_arr' => array());
array_walk_recursive($non_flat_arr, create_function('&$v, $k, &$t', '$t->flat_arr[] = $v;'), $objTmp);
var_dump([ 0 => $objTmp->flat_arr]);
This will give you the output as:
array:1 [
0 => array:3 [
0 => 1
1 => 2
2 => 3
]
]
Hope this helps!
The question might be silly. But I am stucked in here. :( I am getting all of my database value as an object in controller.
This is how I am fetching database value:
$points = $this->CI->modelgraph->get($user_id);
It is getting all of the data corresponding to that user. This is my sample database table from where I am fetching data:
id user_id b_value h_value date r_value
1 24 330 6.2 10.11.2014 90
2 25 334 6.2 10.11.2014 92
This is static data, phpgraphlib provide in the tutorial.
$data = array("1" => .0032, "2" => .0028, "3" => .0021, "4" => .0033,
"5" => .0034, "6" => .0031, "7" => .0036, "8" => .0027, "9" => .0024,
"10" => .0021, "11" => .0026, "12" => .0024, "13" => .0036,
"14" => .0028, "15" => .0025);
I need to extract the fetched data in this manner:
$data = array("h_value" => b_value,);
How could achieve this? What will be the logic? Any help would be really appreciable.
Here is my approach.. but also not complete.. What I am doing wrong?
$total=count($points);
$i=1;
$dataArray=array();
while($i <= $total) {
foreach($points as $value) {
//echo $value -> h_value;
$field = $value -> h_value;
$labels = $value -> b_value;
$dataArray[$i][$field ] = $labels;
$i++;
}
}
When I var_dump($dataArray); Its giving me this output:
array(11) { [1]=> array(1) { ["6.6"]=> string(3) "358" } [2]=> array(1) { ["7.4"]=> string(3) "201" } [3]=> array(1) { ["6.5"]=> string(3) "144" } [4]=> array(1) { ["6.5"]=> string(3) "112" } [5]=> array(1) { ["6.2"]=> string(3) "144" } [6]=> array(1) { ["6.2"]=> string(3) "185" } [7]=> array(1) { ["7.0"]=> string(3) "176" } [8]=> array(1) { ["7.5"]=> string(3) "234" } [9]=> array(1) { ["6.5"]=> string(3) "365" } [10]=> array(1) { ["6.2"]=> string(3) "110" } [11]=> array(1) { ["4.2"]=> string(3) "100" } }
But When I var_dump($data); Its giving this:
array(15) { [1]=> float(0.0032) [2]=> float(0.0028) [3]=> float(0.0021) [4]=> float(0.0033) [5]=> float(0.0034) [6]=> float(0.0031) [7]=> float(0.0036) [8]=> float(0.0027) [9]=> float(0.0024) [10]=> float(0.0021) [11]=> float(0.0026) [12]=> float(0.0024) [13]=> float(0.0036) [14]=> float(0.0028) [15]=> float(0.0025) }
Its clearly visible I have messed up . Where is the wrong ?
Here is the output I print_r($points); Its giving this:
Array ( [0] => stdClass Object ( [id] => 12 [user_id] => 24 [b_value] => 358 [h_value] => 6.6 [rec_date] => 2014-09-19 [rec_time] => [h_value] => 1[date_added] => 2012-09-19 16:38:05 [date_modified] => 0000-00-00 00:00:00 ) [1] ..........
Please see below code.
It is self-explanatory.
Replace your values accordingly.
<?php
function modelFunction($user_id) {
$this->db->select('h_value, b_value');
$this->db->from('YOUR_TABLE_NAME');
$this->db->where('user_id', $user_id);
$query = $this->db->get();
$arr = array();
if ($query->num_rows()) {
$i=0;
foreach ($query->result_array() as $row) {
extract($row);
$arr[$i][$h_value] = $b_value;
++$i;
}
}
}
?>
Controller:
<?php
$points = $this->CI->modelFunction->get($user_id);
?>
Answer edited as per OP's request:
<?php
$dataArray = array();
for ($i=0 ; $i<= $total ; $i++) {
$value = $points[$i];
$field = $value->h_value;
$labels = $value->b_value;
$dataArray[$i][$field ] = $labels;
$i++;
}
?>
$new_array = array();
foreach($points as $point){
$new_array[] = array(
'id' => $point->id,
'user_id' => $point->user_id
);
}
Nice little helper function:
function object_to_array($data)
{
if (is_object($data)) {
$data = get_object_vars($data);
}
if (is_array($data)) {
return array_map(__FUNCTION__, $data);
}
else {
return $data;
}
}
example usage:
$data['points'] = $this->CI->modelgraph->get($user_id);
$data['points'] = object_to_array($data['points']);
After fetching a result from the database, and preparing the array for the JSON enconde, I face a dilemma on how to reference the array 'data' inside the main array.
The "[0]" by far is an error of my logic...
while ($row =$result->fetch()) {
$name = $row['country'];
$id = $row['id']
$username = $row['username'];
$subtotal = $row['subtotal'];
if ( /* If $id exist in array row['series']}*/ ) {
///?????/////
/// Add array to 'DATA'
////?????////
$rows['series']["$id"]["$name"]['data'][]=array("$username", $subtotal);
}
else {
$rows['series'][]= array('id' => "$id", 'name' => "$name", 'data' => array("$username", $subtotal));
}
The vardump show as follow:
array(1) {
["series"]=>
array(2) {
[0]=>
array(3) {
["id"]=>
string(7) "hn"
["name"]=>
string(8) "HN"
["data"]=>
array(2) {
[0]=>
string(17) "GK_5"
[1]=>
string(5) "86040"
}
}
[1]=>
array(3) {
["id"]=>
string(7) "hn"
["name"]=>
string(8) "HN"
["data"]=>
array(2) {
[0]=>
string(17) "GK_8"
[1]=>
string(5) "20358"
}
}
}
}
But I want to add the last item with same id/name like this:
array(1) {
["series"]=>
array(2) {
[0]=>
array(3) {
["id"]=>
string(7) "hn"
["name"]=>
string(8) "HN"
["data"]=>
array(2) {
[0]=>
string(17) "GK_5"
[1]=>
string(5) "86040"
}
array(2) {
[0]=>
string(17) "GK_8"
[1]=>
string(5) "20358"
}
}
}
}
The most natural way would be to change your data structure a bit, so that the series array is indexed by the row ID instead of an arbitrary running index. The would allow you to rewrite your loop to (using mysqli syntax as an example):
$stmt->bind_result($id, $country, $username, $subtotal);
$series = array();
while ( $stmt->fetch() ) {
$series[$id]['country'] = $country;
$series[$id]['data'][] = array(
'username' => $username,
'subtotal' => $subtotal,
);
}
which will give you a data structure like:
$series = array(
'hn' => array(
'country' => 'HN',
'data' => array(
0 => array(
'username' => 'GK_5',
'subtotal' => 86040
),
1 => array(
'username' => 'GK_8',
'subtotal' => 20358
),
// ...
)
),
// ...
);
If you need the data in the exact format shown in your post, you can of course loop over this array with foreach to transform it, e.g.:
$rows = array();
foreach ( $series as $id => $record ) {
$record['id'] = $id;
$rows['series'][] = $record;
}
I'm trying to create a multidimensional array from a form post. This is the dump from that post:
array(8) {
["check"]=>
int(1)
["option_page"]=>
string(19) "content_boxes_group"
["action"]=>
string(6) "update"
["_wpnonce"]=>
string(10) "0adb157142"
["_wp_http_referer"]=>
string(39) "/wp-admin/themes.php?page=home-settings"
["title"]=>
array(3) {
[1]=>
string(9) "Downloads"
[2]=>
string(7) "Columns"
[3]=>
string(4) "Apps"
}
["id"]=>
array(3) {
[1]=>
string(21) "k2-settings-downloads"
[2]=>
string(19) "k2-settings-columns"
[3]=>
string(16) "k2-settings-apps"
}
["order"]=>
array(3) {
[1]=>
string(1) "1"
[2]=>
string(1) "2"
[3]=>
string(1) "3"
}
}
I'm trying to make it look like this:
array(
array('title' => 'Downloads', 'id' => 'k2-settings-downloads', 'order' => '1'),
array('title' => 'Columns', 'id' => 'k2-settings-columns', 'order' => '2'),
array('title' => 'Apps', 'id' => 'k2-settings-apps', 'order' => '3')
);
How can I do this?
something like this?
$post = $_POST['your_array'];
$output = array();
$titles = $post['title'];
$ids = $post['id'];
$orders = $post['order'];
foreach($titles as $id => $title){
$output[] = array("title"=>$title,"id"=>$ids[$id],'order'=>$orders[$id]);
}
I have an array with several rows containing those values (id,date,latlng,transport). I want to remove the entire row when transport = "".
I tried while, for and foreach but the problem is : when I find more than 1 entry to delete, the "$i" doesn't match anymore with the appropriate row.
for($i=0;$i<count($json_a[data][entrees]);$i++)
{
if($json_a[data][entrees][$i][transport]!="")
{
array_splice($json_a[data][entrees],$i,1);
//first removal is OK. Second won't scope the good row
}
}
I managed to make it work by creating a second array and copying the good rows inside, then replacing the first array. But there are probably better solutions, aren't they ?
there is no $i in a foreach loop.
foreach($json_a['data']['entrees'] as $entryKey => $entry){
if($entry['transport']!=""){
unset($json_a['data']['entrees'][$entryKey]);
}
}
for($i=0;$i<count($json_a[data][entrees]);$i++)
{
if($json_a[data][entrees][$i][transport]=="")
{
unset($json_a[data][entrees][$i]);
}
}
print_r($json_a[data][entrees])
Hope this helps!
Try this:
foreach( $json_a['data']['entrees'] as $key => $entry ){
if( $entry['transport'] != "" ){
array_splice($json_a['data']['entrees'], $key, 1);
}else{
unset($json_a['data']['entrees'][$key]);
}
}
You are using PHP array_splice where it reads:
Remove a portion of the array and replace it with something else
To remove one entry from an Array, you should use PHP unset where it reads:
Unset a given variable.
So, your code should be:
<?php
for($i=0;$i<count($json_a[data][entrees]);$i++)
{
if($json_a[data][entrees][$i][transport]!="")
{
//remove this entry from the array
unset($json_a[data][entrees][$i]);
}
}
?>
Test Case:
// Sample Array with 4 entries
$json_a = array(
"data" => array (
"entrees" => array(
array (
"id" => 14,
"date" => '2012-06-14',
"latlng" => '14.000000, -9.00000',
"transport" => ''
),
array(
"id" => 13,
"date" => '2012-06-14',
"latlng" => '13.000000, -8.00000',
"transport" => '12'
),
array(
"id" => 12,
"date" => '2012-06-14',
"latlng" => '12.000000, -7.00000',
"transport" => '45'
),
array(
"id" => 11,
"date" => '2012-06-14',
"latlng" => '11.000000, -6.00000',
"transport" => ''
)
)
)
);
Control Output:
var_dump($json_a);
Outputs:
array(1) { ["data"]=> array(1) { ["entrees"]=> array(4) { [0]=> array(4) { ["id"]=> int(14) ["date"]=> string(10) "2012-06-14" ["latlng"]=> string(19) "14.000000, -9.00000" ["transport"]=> string(0) "" } 1=> array(4) { ["id"]=> int(13) ["date"]=> string(10) "2012-06-14" ["latlng"]=> string(19) "13.000000, -8.00000" ["transport"]=> string(2) "12" } 2=> array(4) { ["id"]=> int(12) ["date"]=> string(10) "2012-06-14" ["latlng"]=> string(19) "12.000000, -7.00000" ["transport"]=> string(2) "45" } [3]=> array(4) { ["id"]=> int(11) ["date"]=> string(10) "2012-06-14" ["latlng"]=> string(19) "11.000000, -6.00000" ["transport"]=> string(0) "" } } } }
Run the Cycle:
for($i=0;$i<count($json_a[data][entrees]);$i++)
{
if($json_a[data][entrees][$i][transport]!="")
{
//remove this entry from the array
unset($json_a[data][entrees][$i]);
}
}
Confirmation Output:
var_dump($json_a);
Outputs:
array(1) { ["data"]=> array(1) { ["entrees"]=> array(2) { [0]=> array(4) { ["id"]=> int(14) ["date"]=> string(10) "2012-06-14" ["latlng"]=> string(19) "14.000000, -9.00000" ["transport"]=> string(0) "" } [3]=> array(4) { ["id"]=> int(11) ["date"]=> string(10) "2012-06-14" ["latlng"]=> string(19) "11.000000, -6.00000" ["transport"]=> string(0) "" } } } }