Inserting a key value pair after a certain key value in PHP - php

I am trying to insert a key value pair at the end of an array of values retrieved from a database query. I tried array_splice but that wasn't doing exactly what I wanted, so I'm trying array_push but it's not adding it to the array.
Here is my code:
public function listFriendsStatus()
{
// get the friend statuses of the logged in user
$connection = $this->sql->getAdapter()->getDriver()->getConnection();
$query = $connection->execute("SELECT status.id, status, time_status, members.username FROM status
INNER JOIN friends ON friends.friend_id = status.id
INNER JOIN members ON members.id = status.id
WHERE friends.user_id = " . $this->getUserId()['id']);
if ($query->count() > 0) {
$status_holder = array();
foreach ($query as $key => $value) {
$status_holder[$key] = $value;
$status_dir = '/images/profile/' . $status_holder[$key]['username'] . '/status/' . $status_holder[$key]['time_status'] . '/';
$real_dir = getcwd() . '/public/' . $status_dir;
if (is_dir($real_dir)) {
$images = array_diff(scandir($real_dir, 1), array('.', '..'));
array_push($status_holder, array('images' => $images));
} else {
array_push($status_holder, array('images' => ''));
}
}
return $status_holder;
} else {
throw new FeedException("No friend statuses were found.");
}
}
For a better explanation, here is a var_export of my array
array ( 0 => array ( 'id' => '2', 'status' => 'this is jimmy, test', 'time_status' => '0', 'username' => 'jimmy', ), 1 => array ( 'id' => '3', 'status' => 'this is jimmy 2, test', 'time_status' => '0', 'username' => 'timmy', ), 2 => array ( 'images' => '', ), )
What I am trying to do is insert after each ["username"] key and value, the images key and value from the images array.
Any help would be appreciated.
Thanks!
(I can try and make the question clearer if need be)
update
$status_holder[$key]['images'] = $images;
did what I need.

If your foreach is retrieving a row at a time, then add the image into this data and then build your other array...
foreach ($query as $key => $value) {
$status_dir = '/images/profile/' . $value['username'] . '/status/' . $value['time_status'] . '/';
$real_dir = getcwd() . '/public/' . $status_dir;
if (is_dir($real_dir)) {
$images = array_diff(scandir($real_dir, 1), array('.', '..'));
$value['images'] = $images;
} else {
$value['images'] = '';
}
$status_holder[$key] = $value;
}

Related

how to cek array php

I have an array that I will insert into the item table, here I use multiple inserts
Array
(
[0] => Array
(
[id_service] => 2
[tracking_number] => RJC219384044389234035
)
[1] => Array
(
[id_service] => 1
[tracking_number] => RJC749944771469498146
)
)
in the item table, there is already id_service: 2
how to make validation, when one of the input is already in the item table, then all the input is false so it fails?
my code
public function nyobain()
{
$resi = $this->input->post('kode'); //tracking_number
$expld = explode(' ', $resi);
$data = $this->M_outbound_destinasi->dbGet($expld); //get 'id_service' where tracking_number
// $db = $this->db->query("SELECT id_service FROM `tabel_items`")->result();
// foreach ($db $key) {
// $temp=array($key->id_service);
// }
// how to cek ? if id_service already in the item table
foreach ($data as $key) {
$idnya = $key['id_service'];
$id_outbound = $key['id_outbound'];
$id_indes = $key['id_indes'];
$id_outbag = $key['id_outbag'];
$data_insert = array(
'jenis' => 'outbound-destinasi',
'id_service' => $idnya,
'id_indes' => $id_indes,
'id_outbound' => $id_outbound,
'id_outbag' => $id_outbag,
'id_admin' => $this->session->userdata('ses_id')
);
$this->db->insert('tabel_items', $data_insert);
}
echo json_encode($data);
}
You can use in_array to achieve this
public function nyobain(){
$resi = $this->input->post('kode');
$expld = explode(' ', $resi);
$data = $this->M_outbound_destinasi->dbGet($expld);
$db = $this->db->query("SELECT id_service FROM `tabel_items`")->result();
if(isset($data) && $data !== ''){//check if $data has a value and it not null
if (in_array($data ,$db, true)) {
return $data.'already exists in the DB!';
}else{
foreach ($data as $key) {
$idnya = $key['id_service'];
$id_outbound = $key['id_outbound'];
$id_indes = $key['id_indes'];
$id_outbag = $key['id_outbag'];
$data_insert = [
'jenis' => 'outbound-destinasi',
'id_service' => $idnya,
'id_indes' => $id_indes,
'id_outbound' => $id_outbound,
'id_outbag' => $id_outbag,
'id_admin' => $this->session->userdata('ses_id')
];
$this->db->insert('tabel_items', $data_insert);
}
return json_encode($data);
}
}
}

How can I return a PHP $_POST array as string that is usable as a name attribute?

Question:
I have an array of post values that looks like:
$_POST['children'] = array(
[0]=>array(
'fname' => 'name',
'mname' => 'mname',
'lname' => 'lname,
'dob' => '10/17/1992
),
[1]=>array(
'fname' => 'name',
'mname' => 'mname',
'lname' => 'lname,
'dob' => '10/17/1992
),
[2]=>array(
'fname' => 'name',
'mname' => 'mname',
'lname' => 'lname,
'dob' => '10/17/1992
)
);
// and so on
I have a script set up in my my view functions that checks for old input, and repopulates the values in the case that the form does not validate. I need to find a way to return the above array as a series of key/value pairs i.e.
'children[0][fname]' = 'name'
'children[0][mname]' = 'mname'
'children[0][lname]' = 'lname'
// ... and so on for all fields
Ideally, I would like this to work with an array of any depth, which makes me think I need some sort of recursive function to format the keys. I am having a terrible time getting my head around how to do this.
What I have tried
I have been working with the following function:
function flatten($post_data, $prefix = '') {
$result = array();
foreach($post_data as $key => $value) {
if(is_array($value)) {
if($prefix == ''){
$result = $result + flatten($value, $prefix. $key );
}else{
$result = $result + flatten($value, $prefix. '[' . $key . ']');
}
}
else {
$result[$prefix . $key .''] = $value;
}
}
return $result;
}
This gets me somewhat close, but isn't quite right. It returns the following when I feed it my $_POST array
[children[1]fname] => test
[children[1]mname] => test
[children[1]lname] => test
[children[1]dob] =>
// Expecting: children[1][fname] => test
// ...
Or is there potentially an easier way to accomplish this?
What ended up working for me:
function flatten($post_data, $prefix = '') {
$result = array();
foreach($post_data as $key => $value) {
if(is_array($value)) {
if($prefix == ''){
$result = $result + flatten($value, $prefix. $key );
}else{
$result = $result + flatten($value, $prefix. '[' . $key . ']');
}
}
else {
if( $prefix == ''){
$result[$prefix . $key.''] = $value;
}else{
$result[$prefix . '['.$key.']'.''] = $value;
}
}
}
return $result;
}
it wasn't accounting for the return value of the last call of the recursive function being a scalar value. The addition of these this if/else statement seems to have resolved it.
if( $prefix == ''){
$result[$prefix . $key.''] = $value;
}else{
$result[$prefix . '['.$key.']'.''] = $value;
}

Converting array key to multidimensional array

I have an array like below
$db_resources = array('till' => array(
'left.btn' => 'Left button',
'left.text' => 'Left text',
'left.input.text' => 'Left input text',
'left.input.checkbox' => 'Left input checkbox'
));
I need to convert this array dynamically like below
'till' => array(
'left' => array(
'btn' => 'Left button',
'text' => 'Left text',
'input' => array(
'text' => 'Left input text',
'checkbox' => 'Left input checkbox'
)
)
)
I tried the key with explode. it works if all the key has only one ".". But the key has dynamic one. so please hep me to convert the array dynamically. I tried this Below Code
$label_array = array();
foreach($db_resources as $keey => $db_resources2){
if (strpos($keey,'.') !== false) {
$array_key = explode('.',$keey);
$frst_key = array_shift($array_key);
if(count($array_key) > 1){
$label_array[$frst_key][implode('.',$array_key)] = $db_resources2;
//Need to change here
}else{
$label_array[$frst_key][implode('.',$array_key)] = $db_resources2;
}
}
}
There might be more elegant ways to go about it, but here is one example of doing it with recursive helper function:
function generateNew($array, $keys, $currentIndex, $value)
{
if ($currentIndex == count($keys) - 1)
{
$array[$keys[$currentIndex]] = $value;
}
else
{
if (!isset($array[$keys[$currentIndex]]))
{
$array[$keys[$currentIndex]] = array();
}
$array[$keys[$currentIndex]] = generateNew($array[$keys[$currentIndex]], $keys, $currentIndex + 1, $value);
}
return $array;
}
$result = array();
// $temp equals your original value array here...
foreach ($temp as $combinedKey => $value)
{
$result = generateNew($result, explode(".", $combinedKey), 0, $value);
}

How can I fix this query to return only items with a certain value in its subarray?

I'm trying to modify a voting script(Thumbsup) I need this query to only return only array items that have their 'cat' => '1' in the subarray (proper term?)
<?php $items = ThumbsUp::items()->get() ?>
Here's an example of the live generated array from my database
array (
0 =>
array (
'id' => 1,
'name' => 'a',
'cat' => '1',
),
1 =>
array (
'id' => 2,
'name' => 'b',
'cat' => '2',
),
2 =>
array (
'id' => 3,
'name' => 'c',
'cat' => '2',
),
)
Is this possible by just modifying the query?
edit: heres function get()
public function get()
{
// Start building the query
$sql = 'SELECT id, name, url, cat, closed, date, votes_up, votes_down, ';
$sql .= 'votes_up - votes_down AS votes_balance, ';
$sql .= 'votes_up + votes_down AS votes_total, ';
$sql .= 'votes_up / (votes_up + votes_down) * 100 AS votes_pct_up, ';
$sql .= 'votes_down / (votes_up + votes_down) * 100 AS votes_pct_down ';
$sql .= 'FROM '.ThumbsUp::config('database_table_prefix').'items ';
// Select only either open or closed items
if ($this->closed !== NULL)
{
$where[] = 'closed = '.(int) $this->closed;
}
// Select only either open or closed items
if ($this->name !== NULL)
{
// Note: substr() is used to chop off the wrapping quotes
$where[] = 'name LIKE "%'.substr(ThumbsUp::db()->quote($this->name), 1, -1).'%"';
}
// Append all query conditions if any
if ( ! empty($where))
{
$sql .= ' WHERE '.implode(' AND ', $where);
}
// We need to order the results
if ($this->orderby)
{
$sql .= ' ORDER BY '.$this->orderby;
}
else
{
// Default order
$sql .= ' ORDER BY name ';
}
// A limit has been set
if ($this->limit)
{
$sql .= ' LIMIT '.(int) $this->limit;
}
// Wrap this in an try/catch block just in case something goes wrong
try
{
// Execute the query
$sth = ThumbsUp::db()->prepare($sql);
$sth->execute(array($this->name));
}
catch (PDOException $e)
{
// Rethrow the exception in debug mode
if (ThumbsUp::config('debug'))
throw $e;
// Otherwise, fail silently and just return an empty item array
return array();
}
// Initialize the items array that will be returned
$items = array();
// Fetch all results
while ($row = $sth->fetch(PDO::FETCH_OBJ))
{
// Return an item_id => item_name array
$items[] = array(
'id' => (int) $row->id,
'name' => $row->name,
'url' => $row->url,
'cat' => $row->cat,
'closed' => (bool) $row->closed,
'date' => (int) $row->date,
'votes_up' => (int) $row->votes_up,
'votes_down' => (int) $row->votes_down,
'votes_pct_up' => (float) $row->votes_pct_up,
'votes_pct_down' => (float) $row->votes_pct_down,
'votes_balance' => (int) $row->votes_balance,
'votes_total' => (int) $row->votes_total,
);
}
return $items;
}
thanks.
You can easily modify "get()" to add the desired functionality:
public function get($cat = null)
{
$where = array();
if ($cat !== null) {
$where[] = 'cat = '. (int) $cat;
}
// ... original code ...
}
Usage:
$items = ThumbsUp::items()->get(1);

Help with Array List - PHP MYSQL

I have an array value like this.
My print_r($_POST) looks like this.
I can get the post count value too. (Here the count value is 3)
Array ( [tag] => Array ( [4-a] => User1 [8-a] => User2 [3-a] => User3 ))
Now, i want the above array values in a single string.
For ex:
$all_users = User1,User2,User3
Is this possible . Pl advice.
Haan
$all_users = implode(',',$your_array);
If i understand your question well...
$array = Array ( 'tag' => Array ( '4-a' => 'User1', '8-a' => 'User2', '3-a' => 'User3' ));
$allUsers = '';
$first = true;
foreach($array['tag'] as $key=>$value) {
if($first == false) {
$allUsers .= ',' . $value;
} else {
$allUsers .= $value;
}
$first = false;
}
echo $allUsers;

Categories