Different positions in array - php

I have an sql query which outputs an array the output looks like this
Array
(
[0] => Array
(
[customer_id] => 7
[language_id] => 1
[variableitem_id] => 13
[name] => QUESTION_HEADLINE
[value] => Bitte geben Sie Ihren Downloadkey ein:
)
[1] => Array
(
[customer_id] => 7
[language_id] => 1
[variableitem_id] => 15
[name] => QUESTION_BUTTON
[value] => Start!
)
[2] => Array
(
[customer_id] => 7
[language_id] => 1
[variableitem_id] => 6
[name] => PAGETITLE
[value] => Steigenberger Hotels and Resorts - Mediathek
)
)
In my controller I get it as
$data['variables_data'] = $this->Home_model->getVariables($customer_id, $language_id);
Now for different ids in the url like for
localhost/home/user/12 and localhost/home/user/14
the positions of the variable differs
for example in my view when I echo
$variable[0]['value']
it gives QUESTION_HEADLINE for one user and PAGE_TITLE for the other .
Is it possible to make them same for all of the user like if I echo
$variable[0]['value']
it should return me QUESTION_HEADLINE every time and for every user
Code for Home model get_variables function
function getVariables($customer_id, $language_id) {
$query = $this->db->query("SELECT customers_idcustomers AS customer_id,
languages_idlanguages AS language_id,
variableitems_idvariableitems AS variableitem_id,
variableitem AS name,
variabletext AS value
FROM variables v
LEFT JOIN variableitems vi ON v.variableitems_idvariableitems = vi.idvariableitems
WHERE v.customers_idcustomers ='" . $customer_id . "'
AND v.languages_idlanguages =" . $language_id
);
$var = $query->result_array();
return $var;
}
Thanks in advance

You can set it explicitly, like
foreach($outArray as $output)
{
$output['name']="Any thing you want";
}

So , as i understand you want to make reduce your output to one dimension. It can be done with MYSQL also. Here php version:
In your controller
$data = $this->Home_model->getVariables($customer_id, $language_id);
$data['variables'] = array(
'customer_id' => $data[0]['customer_id'],
'language_id' => $data[0]['language_id'],
'variableitem_id' => array(),
'name' => array(),
'value' => array()
);
foreach($data as $k => $v) {
$data['variables']['variableitem_id'][] = $v['variableitem_id'];
$data['variables']['name'][] = $v['name'];
$data['variables']['value'][] = $v['value'];
}
And in your view
echo $variables['value'][2].' '.$variables['value'][3];
//do whatever you want

Related

PHP - Array does not turn into two-dimensional array

I need to make my array better.
I am getting data from database and i have milestones and milestone_parts. i want two-dimensional array. I need data of milestones in the first dimension and milestone_parts in the second dimension.
With this code:
$query = "
SELECT
a.id AS `milestone_id`,
a.titel AS `milestone_titel`,
a.client AS `client`,
a.verkocht_id AS `milestone_verkocht_id`,
b.id AS `milestonefase_id`,
b.titel AS `milestonefase_titel`,
b.milestone_id AS `milestonefase_milestone_id`,
b.omschrijving AS `milestonefase_omschrijving`
FROM `milestones` a
INNER JOIN `milestone_parts` b ON a.id=b.milestone_id
WHERE a.verkocht_id = '99'
";
$result= $db->query($dbh, $query);
while ($row = $db->fetchassoc($result))
{
$stone = array($row['milestone_verkocht_id'], $row['milestone_id'], $row['milestone_titel'], $row['client']);
$fase = array($row['milestonefase_milestone_id'],$row['milestonefase_id'],$row['milestonefase_titel']);
$stone[] = $fase;
echo '<pre>'; print_r($stone); echo '</pre>';
}
I get this as result
Array
(
[0] => 99
[1] => 6
[2] => string
[3] => string
[4] => Array
(
[0] => 6
[1] => 10
[2] => string
)
)
Array
(
[0] => 99
[1] => 6
[2] => string
[3] => string
[4] => Array
(
[0] => 6
[1] => 11
[2] => string
)
)
but I need (with names) this:
Array
(
[milestone_verkocht_id] => 99 // This is project id
[milestone_id] => 6
[milestone_title] => string
[client] => string
[10] => Array
(
[milestonefase_milestone_id] => 6
[milestonefase_id] => 10
[milestone_title] => string
)
[11] => Array
(
[milestonefase_milestone_id] => 6
[milestonefase_id] => 11
[milestone_title] => string
)
[12] => Array
(
[milestonefase_milestone_id] => 6
[milestonefase_id] => 12
[milestone_title] => string
)
)
Can you help me or do you have a solution? Help me please!
you can cycle each field returned by the query, checking the field name and making new arrays
$stones = array();
while ($row = $db->fetchassoc($result)) {
$fase = array();
$stone = array('milestones' => array());
foreach ($row as $k => $v) {
if (strpos($k, 'milestonefase_') === 0) {
$fase[$k] = $v;
} else {
$stone[$k] = $v;
}
}
if(!isset($stones[$stone['milestone_id']])) {
$stones[$stone['milestone_id']] = $stone;
}
$stones[$stone['milestone_id']]['milestones'][$fase['milestonefase_id']] = $fase;
}
echo '<pre>'.print_r($stones, true).'</pre>';
Edit
made some changes in order to match the request. Now we use $stones to store the information we already have on a milestone, adding to it the different "$fase" returned from the query
Probably a more clean way is to retrieve all the information with two different queries one for milestones and the other for the fases
Edit2
Added a sub-array for the milestone fases

getting filtered array from array with condition php

This codes are with Codeigniter framework,
I have below array $csv_array
Array ( [0] => Array ( [location] => X33 [usernumber] => 1 [order] => XX [part_number] => Hi ) [1] => Array ( [location] => X33 [usernumber] => 1 [order] => XX [part_number] => 68730 ) [2] => Array ( [location] => W33 [usernumber] => 2 [order] => YY [part_number] => 68741) [3] => Array ( [location] => W33 [usernumber] => 2 [order] => YY [part_number] => Hello )
My requirements,
create an array for each usernumber(here 2 different user) which contains location, part_number, order and then send email only 2 times, 1 to each user with information of array generated for usernumber,
I tried below step code but i lost in loops!
foreach ($csv_array as $row)
{
$user = $this->admin_model->get_usershipment($row['usernumber']);
$order_data = array();
for ($i=0; $i < count($csv_array); $i++)
{
if($row['usernumber'] == $user->usernumber)
{
//Create some array to send????
$order_data = array();
//Should be something like below, but should contain for usernumber 1 only, and then in 2nd email it should be for usernumber 2 only
//$order_data = array('location' => $row['location'], 'part_number' => $row['part_number'], 'order' => $row['order']);
}
}
$data = array(
'user_firstname' => $user->user_firstname,
'user_email' => $user->user_email,
'order_data' => $order_data);
$subject = 'Hello Update! ';
$message = $this->parser->parse('templates/notification', $data, TRUE);
$this->emailnotification($user->user_email, $subject, $message);
}
One more problem here is that emailnotification fuction will run 4 times, which i want only for 2 time, means to 2 users only,
Any guide how i can achieve this?
Thanks in advance!
There can be many approaches if i understand you correctly. One solution can be (This is just demo use your own sense to modify it):-
foreach($csv_array as $row)
{
$csv_array1[$row['usernumber']][] = $row
}
foreach ($csv_array1 as $key=>$details)
{
$user = $this->admin_model->get_usershipment($key);
$data = array(
'user_firstname' => $user->user_firstname,
'user_email' => $user->user_email,
'order_data' => $details);//$details has 2 arrays for each user
$subject = 'Hello Update! ';
$message = $this->parser->parse('templates/notification', $data, TRUE);
$this->emailnotification($user->user_email, $subject, $message);
}

How to get array values in codeigniter using explode method

Query run is based on 2 id, however I get one output value
Input:
public function get_place_order_category($id)
{
/* $id = 1,2;*/
$ids = explode(',',$id);
foreach($ids as $catid)
{
$this->db->where('product_id =',trim($catid));
$query = $this->db->get('products');
return $query->result_array();
}
}
Output:
Array
(
[0] => Array
(
[product_id] => 12
[product_name] => Product1
[product_code] => pro12345
[product_price] => 200.00
[product_newprice] => 0.00
[size] => 0-6M , 0-9M ,9-12M
[product_front] => 1446200664.JPG
[product_back] => 14462006641.JPG
[product_left] => 14462006642.JPG
[product_right] => 14462006643.JPG
[product_description] =>
[styling_tips] =>
[category_id] => 62
[user_id] => 5
[status] => 1
[parent_id] => 42
[qty] => 4
[promo_id] => 0
[etc4] => 0
[etc5] => 0
)
)
You can use one global array and add result arrays to it. Try this:
public function get_place_order_category($id)
{
/* $id = 1,2;*/
//first test here what comes in $id
echo $id."<br/>";
$ans_arr = array();
$ids = explode(',',$id);
/*test here too whats actually happens after explode weather
arrayhas generated and what are the element of it */
echo "<pre>";print_r($ids);echo "<br/>";
foreach($ids as $catid)
{
$this->db->where('product_id =',trim($catid));
$query = $this->db->get('products');
$ans_arr[] = $query->result_array();
}
return $ans_arr;
}

Loop logic help needed - Can't compare correctly

I have the following table:
And I use this function to get data from it:
function get_cart_by($player_id)
{
global $db;
$sql = 'SELECT DISTINCT(item_id) FROM ' . PCP_MARKET_CART . '
WHERE player_id = ' . (int) $player_id;
$result = $db->sql_query($sql);
$rowset = $db->sql_fetchrowseT($result);
$db->sql_freeresult($result);
$cart = array();
foreach ($rowset as $item)
{
$cart[] = $item['item_id'];
}
return $cart;
}
The result looks like this:
Array
(
[0] => 16
[1] => 17
[2] => 49
[3] => 48
[4] => 18
[5] => 19
[6] => 51
)
Now I have an array that lists all my products from another table without looking at the player_id. I want to use the array demonstrated above and add a custom class to the items that do not use the player_id, like show which items the user already has on cart.
The other array that lists all the products looks like this:
Array
(
[0] => Array
(
[item_id] => 16
[parent_id] => 11
[cat_position] => 0
[item_position] => 1
[item_type] => product
[item_title] => Custom Business
[item_description] => Some description
[item_price] => 9.99
[item_units] => 500
[item_preview] => http://i.imgur.com/3eCpMMm.png
[times_sold] => 0
[daopay_url] => http://i.imgur.com/QA7bBfJ.jpg
[public] => 1
[time] => 1384709635
)
[1] => Array
(
[item_id] => 17
[parent_id] => 11
[cat_position] => 0
[item_position] => 1
[item_type] => product
[item_title] => Custom Business
[item_description] => Some description
[item_price] => 9.99
[item_units] => 500
[item_preview] => http://i.imgur.com/3eCpMMm.png
[times_sold] => 0
[daopay_url] => http://i.imgur.com/QA7bBfJ.jpg
[public] => 1
[time] => 1384709635
)
[2] => Array
(
[item_id] => 49
[parent_id] => 11
[cat_position] => 0
[item_position] => 1
[item_type] => product
[item_title] => Custom Business
[item_description] => Some description
[item_price] => 9.99
[item_units] => 500
[item_preview] => http://i.imgur.com/3eCpMMm.png
[times_sold] => 0
[daopay_url] => http://i.imgur.com/QA7bBfJ.jpg
[public] => 1
[time] => 1384709635
)
)
Now based on the first array, I want to mark the same item IDs on the second arrays and show that they are different (on cart).
I have tried quite a lot and for some reason, I managed to mark only item_id 16 and 17, the rest are not getting "marked" for some reason.
This is the code I used:
$cartar = $market->get_cart_by($user->data['player_id']);
$cartln = sizeof($cartar) - 1;
// Fetch items of the selected category
$items = $market->fetch_cat_items($cat_id); // Equivalent to the array above
$index = 0;
print_r($items);
foreach ($items as $item)
{
$name = $item['item_name'];
if ($cartln >= $index)
{
if ($cartar[$index] == $item['item_id'])
$name .= $cartar[$index];
}
echo $name;
$index++;
}
I tried to make the example explain my case the best way possible. So, when I echo out $name it only outputs thename16 and thename17 (those two), but it doesn't continue to 49 and so on.
Please be aware that the array with all the products in it is quite large, I made it shorter for demonstration purposes only.
Were am I failing in my code? Why are only the first two items getting "marked"? I'm quite in a hurry right now, once I get back from a meeting I'll try to explain my issue further.
i don't know if i understood correctly but maybe you want to do it like this:
foreach ($items as $item) {
$name = $item['item_name'];
if(in_array($item['item_id'],$cartar)) {
$name .= $item['item_id'];
}
echo $name;
}
used in_array() to check if the item_id exists somewhere in $cartar. No matter on which position in array.

Why the value of first element only is getting displayed?

I'm having two arrays i'm inserting one array into another. This operation is done for each element of first array using foreach loop. But I'm able to attach only first pair of key value pairs to the first array during second iteration it does not. Can you help me in achieving this for aal array elements? My code is as follows:
$data = $grid->GetData();
//print_d($data);
foreach($data as $key => $value) {
$sql =" SELECT users_details.user_state, users_details.user_city FROM ".TBL_USERS." AS user JOIN ";
$sql .= TBL_USERS_DETAILS." AS users_details on user.user_id = users_details.user_id ";
$sql .=" WHERE user.user_id = '". $value['user_id']."'" ;
$gDb->Query( $sql );
$user_data = $gDb->FetchArray(MYSQL_FETCH_SINGLE);
$data[$key]['user_state'] = $user_data['user_state'];
$data[$key]['user_city'] = $user_data['user_city'];
}
The first array named $data is as follows:
Array
(
[0] => Array
(
[user_id] => 9def02e6337b888d6dbe5617a172c18d
[user_first_name] => Ashutosh
[user_last_name] => Modi
[user_email] => ashutosh.modi#gmail.com
[user_status] => enable
[user_subscription] => lifetime
[user_registered_type] => online
[user_reg_date] => 1325581397
)
[1] => Array
(
[user_id] => a6d22e4cc3f65778a60b359842bcec82
[user_first_name] => Dilip
[user_last_name] => Modi
[user_email] => dm.modi#gmail.com
[user_status] => enable
[user_subscription] => period
[user_registered_type] => online
[user_reg_date] => 1325152066
)
)
The first iteration of second array named $user_data is as follows:
Array
(
[user_state] => Rajasthan
[user_city] => Jhunjhunu
)
Now after attaching this the array $data becomes as follows:
Array
(
[0] => Array
(
[user_id] => 9def02e6337b888d6dbe5617a172c18d
[user_first_name] => Ashutosh
[user_last_name] => Modi
[user_email] => ashutosh.modi#gmail.com
[user_status] => enable
[user_subscription] => lifetime
[user_registered_type] => online
[user_reg_date] => 1325581397
[user_state] => Rajasthan
[user_city] => Jhunjhunu
)
[1] => Array
(
[user_id] => a6d22e4cc3f65778a60b359842bcec82
[user_first_name] => Dilip
[user_last_name] => Modi
[user_email] => dm.modi#gmail.com
[user_status] => enable
[user_subscription] => period
[user_registered_type] => online
[user_reg_date] => 1325152066
[user_state] =>
[user_city] =>
)
)
I'm not getting why the second array is having the blank values for user_state and user-city. Even after having the values of the array $user_data in second iterations are as follows:
Array
(
[user_state] => Arunachal Pradesh
[user_city] => Shollong
)
Can you resolve my this issue. Thanks in advance.
user_state and user_city are both added, so your code is working fine. You gotta know why $user_data is empty there.
Make your code like this:
echo $sql;
print_r($user_data);
$data[$key]['user_state'] = $user_data['user_state'];
$data[$key]['user_city'] = $user_data['user_city'];
That will output your sql for each loop and print_r function (or var_dump) will echo $user_data array right before those lines. Check why it is empty. Probably your second query in that loop is not what you think it is.
Your insertion is lie inside array of array. Try this
$i=0;
foreach($data as $key => $value) {
$sql =" SELECT users_details.user_state, users_details.user_city FROM ".TBL_USERS." AS user JOIN ";
$sql .= TBL_USERS_DETAILS." AS users_details on user.user_id = users_details.user_id ";
$sql .=" WHERE user.user_id = '". $value['user_id']."'" ;
$gDb->Query( $sql );
$user_data = $gDb->FetchArray(MYSQL_FETCH_SINGLE);
$data[$i]['user_state'] = $user_data['user_state'];
$data[$i]['user_city'] = $user_data['user_city'];
$i++;
where $i represent the array key inside your data file which is default indexing start from 0 & go to 1,2 & so on in your data file..
Also Explore the following program may be find any thing good & being helpful in form to sort out your problem.
e.g a program to update the array inside array.
<?php
$d3 = array('0'=>array('b'=>'1','c'=>'2'),'1'=>array('b'=>'3','c'=>'4'));
$i=0;
foreach($d3 as $k => $v){
$d3[$i]['b'] = "h";
$i++;
}
print_r($d3);
?>

Categories