Codeigniter extract Object std class and create array - php

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']);

Related

How do I go through a multidimensional array and add a value to each one?

I have an array that is like this:
array(3) {
[0]=>
array(2) {
["id"]=>
string(2) "10"
["name"]=>
string(5) "city1"
}
[1]=>
array(2) {
["id"]=>
string(2) "11"
["name"]=>
string(5) "city2"
}
[2]=>
array(2) {
["id"]=>
string(2) "12"
["name"]=>
string(5) "city3"
}
}
I need to add another value that's called "status" to each of them. So that it basically becomes:
[0]=>
array(3) {
["id"]=>
string(2) "10"
["name"]=>
string(5) "city1"
["status"]=>
string(1) "1"
}
The status is dynamic and may vary for each item, so I need to call a function like this:
$status = getStatus($id);
That $id I am getting also from each item in that array.
How would I do this best? I understand I need to loop through the array, but how do I then add each correct response from getStatus to the correct array item?
Any help is greatly appreciated :)
Try this...
foreach($array $key=>$value){
$array[$key]['status']=1;
}
Demo......
I added a dummy function getStatus just to have an example, since you said that getStatus is dynamic might as well give you an example of that, you just have update to your own need of that function. Try this:
$data =
array(
array(
"id" => "10",
"name" => "city1"
),
array(
"id" => "11",
"name" => "city2"
),
array(
"id" => "13",
"name" => "city3"
)
);
echo '<pre>';
print_r($data);
echo '</pre>';
function getStatus($id) {
if($id == "10") {
$status = "1";
} else if($id == "11") {
$status = "2";
} else if($id == "13") {
$status = "3";
}
return $status;
}
foreach($data as $key => $values) {
$data[$key]["status"] = getStatus($data[$key]["id"]);
}
echo '<pre>';
print_r($data);
echo '</pre>';

multiple arrays in codeigniter session

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);
}

PHP array sort and remove duplicates by two field values

I have an array structure like this
[0]=>array(3) {
["Number"]=> "L1"
["Location"]=> "Location-A"
["Qty"]=>"1"
}
[1]=>array(3) {
["Number"]=> "L1"
["Location"]=> "Location-B"
["Qty"]=> "5"
}
[2]=> array(3) {
["Number"]=> "L1"
["Location"]=> "Location-B"
["Qty"]=> "4"
}
[3]=>array(3) {
["Number"]=> "L2"
["Location"]=> "Location-B"
["Qty"]=> "5"
}
But i required below structure as ouput
[0]=>array(3) {
["Number"]=> "L1"
["Location"]=> "Location-A"
["Qty"]=>"1"
}
[1]=> array(3) {
["Number"]=> "L1"
["Location"]=> "Location-B"
["Qty"]=> "4"
}
[2]=>array(3) {
["Number"]=> "L2"
["Location"]=> "Location-B"
["Qty"]=> "5"
}
How can i remove duplicate value by Number and Location?
ksort only works for one value, i need to remove by two values , how can i achieve this PHP ?
$ordered = array();
foreach ($data as $da)
{
$ordered[$da['Number']] = $da;
$ordered[$da['Location']] = $da;
}
ksort($ordered);
Concatenate the two fields when creating your new array:
foreach ($data as $da) {
$result[$da['Number'] . '.' . $da['Location']] = $da;
}
$result = array_values($result); // Turn it back into indexed array
Try this..
<?php
$array = array(
0 => array('Number'=>'L1','Location'=>'Location-A','Qty'=>'1'),
1 => array('Number'=>'L1','Location'=>'Location-B','Qty'=>'5'),
2 => array('Number'=>'L1','Location'=>'Location-B','Qty'=>'4'),
3 => array('Number'=>'L2','Location'=>'Location-B','Qty'=>'5'),
);
$output = array_values(array_intersect_key($array,array_unique(array_map(function($arrayval) {
return $arrayval['Number'] . '.' .$arrayval['Location'];
}, $array))
));
print_r($output);
Output
Array ( [0] => Array ( [Number] => L1 [Location] => Location-A [Qty] => 1 )
[1] => Array ( [Number] => L1 [Location] => Location-B [Qty] => 5 )
[2] => Array ( [Number] => L2 [Location] => Location-B [Qty] => 5 ) )
Try this:
function array_unique_c($array, Closure $comparer) {
$result = array();
for($i = 0; $i < count($array); $i++) {
$duplicates = false;
for($n = $i + 1; $n < count($array); $n++) {
if ($comparer($array[$i], $array[$n])) {
$duplicates = true;
break;
}
}
if(!$duplicates) {
$result[] = $array[$i];
}
}
return $result;
}
Usage:
$uniqueArray = array_unique_c($a, function ($itemA, $itemB) {
return $itemA['Number'] == $itemB['Number'] && $itemA['Location'] == $itemB['Location'];
});
Output:
array(3) {
[0] => array(3) {
["Number"] => string(2) "L1"
["Location"] => string(10) "Location-A"
["Qty"] => string(1) "1"
}
[1] => array(3) {
["Number"]=> string(2) "L1"
["Location"]=> string(10) "Location-B"
["Qty"]=> string(1) "4"
}
[2]=> array(3) {
["Number"]=> string(2) "L2"
["Location"]=> string(10) "Location-B"
["Qty"]=> string(1) "5"
}
}
Easy way to do this job:
$data = [
["Number"=> "L1","Location"=> "Location-A","Qty"=>"1"],
["Number"=> "L2","Location"=> "Location-B","Qty"=>"6"],
["Number"=> "L3","Location"=> "Location-A","Qty"=>"8"],
["Number"=> "L2","Location"=> "Location-B","Qty"=>"5"],
["Number"=> "L3","Location"=> "Location-A","Qty"=>"2"],
["Number"=> "L1","Location"=> "Location-B","Qty"=>"4"],
["Number"=> "L1","Location"=> "Location-B","Qty"=>"1"],
["Number"=> "L2","Location"=> "Location-B","Qty"=>"3"],
];
foreach ($data as $k=>$v) {
$arr[md5($v['Number'].$v['Location'])] = $v;
}
$result = array_values($arr); //can be omitted
As you can see $arr is equal $result and you can ommit array_values() func

Remove duplicates from multidimensional associative array in php if two values match

I have a multidimensional array of the following structure and I want to remove duplicates from it. For example if the ["amount"] is the same for two ["cities"] but the ["time"] is the same or different then I count this is a duplicate and want to remove this node from the array.
In the following example I want to remove completely node 0 from the array as the city and amount are the same as node 1. They are both Bristol (Bristol, United Kingdom) and 373 Even though the time is different being 17:15 and 17:16.
If the times are different as in this case then I would remove the later time.
array(8) {
[0]=>
array(3) {
["time"]=>
string(5) "17:16"
["city"]=>
string(33) "Bristol (Bristol, United Kingdom)"
["amount"]=>
int(373)
}
[1]=>
array(3) {
["time"]=>
string(5) "17:15"
["city"]=>
string(33) "Bristol (Bristol, United Kingdom)"
["amount"]=>
int(373)
}
[2]=>
array(3) {
["time"]=>
string(5) "17:16"
["city"]=>
string(37) "Wednesbury (Sandwell, United Kingdom)"
["amount"]=>
int(699)
}
[3]=>
array(3) {
["time"]=>
string(5) "17:16"
["city"]=>
string(45) "Wolverhampton (Wolverhampton, United Kingdom)"
["amount"]=>
int(412)
}
[4]=>
array(3) {
["time"]=>
string(5) "17:15"
["city"]=>
string(33) "Swansea (Swansea, United Kingdom)"
["amount"]=>
int(249)
}
[5]=>
array(3) {
["time"]=>
string(5) "17:16"
["city"]=>
string(39) "Watford (Hertfordshire, United Kingdom)"
["amount"]=>
int(229)
}
[6]=>
array(3) {
["time"]=>
string(5) "17:14"
["city"]=>
string(39) "Nottingham (Nottingham, United Kingdom)"
["amount"]=>
int(139)
}
[7]=>
array(3) {
["time"]=>
string(5) "17:13"
["city"]=>
string(31) "Dartford (Kent, United Kingdom)"
["amount"]=>
int(103)
}
}
Try this:
$result = array();
foreach ($array as $place) {
if (!array_key_exists($place['time'], $result)) {
$result[$place['time']] = $place;
}
}
<?php
$data = array(
array(
'time' => '17:16',
'city' => 'Bristol',
'amount' => 373,
),
array(
'time' => '18:16',
'city' => 'Bristol',
'amount' => 373,
),
array(
'time' => '18:16',
'city' => 'Wednesbury',
'amount' => 699,
),
array(
'time' => '19:16',
'city' => 'Wednesbury',
'amount' => 699,
),
);
$tmp = array();
foreach ($data as $row) {
$city = $row['city'];
$amount = $row['amount'];
if (!isset($tmp[$city][$amount])
|| $tmp[$city][$amount]['time'] < $row['time']) {
$tmp[$city][$amount] = $row;
}
}
$data = array();
foreach ($tmp as $cities) {
foreach ($cities as $city) {
$data[] = $city;
}
}
var_dump($data);
Create a 2-dimensional associative array, where one dimension is keyed off the city, and the other is the amount:
$assoc = array();
foreach ($data as $el) {
$city = $el['city'];
$amount = $el['amount'];
if (isset($assoc[$city]) {
$assoc[$city][$amount] = $el;
} else {
$assoc[$city] = array($amount => $el);
}
}
// Now gather up all the elements back into a single array
$result = array();
foreach ($assoc as $cities)
foreach ($cities as $city) {
$result[] = $city;
}
}

PHP array_merge_recursive with numeric keys

So I'm suppose to build a multidimensional array dynamically from a text file, and everything works perfectly except that the numeric keys are screwing me over...
The text file looks something like this:
a=1
b.c=2
b.d.0.e=3
b.d.0.f=4
b.d.1.e=5
b.d.1.f=6
As the array_merge_recursive doesn't work with numeric keys, the output is like:
array(2) {
["a"]=>
string(3) "1"
["b"]=>
array(2) {
["c"]=>
string(3) "2"
["d"]=>
array(4) {
[0]=>
array(1) {
["e"]=>
string(9) "3"
}
[1]=>
array(1) {
["f"]=>
string(4) "4"
}
[2]=> array(1) {
["e"]=>
string(8) "5"
}
[3]=>
array(1) {
["f"]=>
string(9) "6"
}}}}
Is there any easy solution to make the output like...?
array(2) {
["a"]=>
string(3) "1"
["b"]=>
array(2) {
["c"]=>
string(3) "2"
["d"]=>
array(2) {
[0]=>
array(2) {
["e"]=>
string(9) "3"
["f"]=>
string(4) "4"
}
[1]=>
array(3) {
["e"]=>
string(9) "5"
["f"]=>
string(4) "6"
}}}}
Thanks
You could break each bit into its components and build up the array one step at a time.
$path = "b.d.0.e";
$val = 3;
$output = array();
$parts = explode(".", $path);
// store a pointer to where we currently are in the array.
$curr =& $output;
// loop through up to the second last $part
for ($i = 0, $l = count($parts); $i < $l - 1; ++$i) {
$part = $parts[$i];
// convert numeric strings into integers
if (is_numeric($part)) {
$part = (int) $part;
}
// if we haven't visited here before, make an array
if (!isset($curr[$part])) {
$curr[$part] = array();
}
// jump to the next step
$curr =& $curr[$part];
}
// finally set the value
$curr[$parts[$l - 1]] = $val;
My output, using the same input as yours:
Array (
[a] => 1
[b] => Array (
[c] => 2
[d] => Array (
[0] => Array (
[e] => 3
[f] => 4
)
[1] => Array (
[g] => 5
[h] => 6
)
)
)
)
Or you could use eval():
$raw_data = file($txt_file, FILE_IGNORE_NEW_LINES);
foreach ($raw_data as $line) {
list($keys, $value) = explode('=', $line);
$keys = explode('.', $keys);
$arr_str = '$result';
foreach ($keys as $key) {
if (ctype_digit($key)) {
$arr_str .= "[" . $key . "]";
} else {
$arr_str .= "['" . $key . "']";
}
}
eval($arr_str . ' = $value;');
}
print_r($result);
I know this is an old one, but the best solution I have found is to use array_replace_recursive. It will achieve what you are looking to do:
$start = array(
"600" => array("total" => 100),
"700" => array("total" => 200)
);
$finish = array(
"600" => array("average" => 25),
"700" => array("average" => 50)
);
$out = array_replace_recursive($start,$finish);
var_dump($out):
array(2) {
[600]=>
array(2) {
["total"]=>
int(100)
["average"]=>
int(25)
}
[700]=>
array(2) {
["total"]=>
int(200)
["average"]=>
int(50)
}
}

Categories