Create array from MySQL results, and add new items - php

I've got a MySQL search query outputting to an array:
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
What I'd like to be able to is add further keys/values to each array item.
So at the moment it outputs:
array(1) {
[0]=>
array(7) {
["organisation"]=>
string(32) "7a5fddaceecec75c9a13cb329f6b4b15"
["date_created"]=>
string(10) "2017-08-04"
}
}
I'd like it also to include this on the end of the array:
'name' => getName($result['name'];
I assume I do that with array_push and a while loop? I just can't figure out how.
Thanks

If you're going to use array_push() to insert a "$key" => "$value" pair into an array, it can be done using the following:
$data[$key] = $value;
It is not necessary to use array_push.

Related

php- get associative array values

pls, i would like to get the values of the $aa variable, i'm using the mysqli_fetch_all because all the values need to be used in another layer.
Thanks
$aa = mysqli_fetch_all($ttt,MYSQLI_ASSOC);
Output with var_dump($aa):
array(2) { [0]=> array(1) { ["followe"]=> string(8) "bammyww " } [1]=> array(1) { ["followe"]=> string(5) "demo " } }
i have tried using $aa['followe'] , but i'm getting invalid index error.
Just loop through it. It's an array containing associative arrays.
foreach($aa as $item)
{
$item['followe'] // do something with this.
}
Instead of $aa['followe'], try:
$aa[0]['followe'];
as its a multi-dimension array. And the right approach to get all the array element is using foreach() like:
foreach($aa as $item)
{
$item['followe']
}
use
$aa[0]['followe'];
$aa[0] is array(1) { ["followe"]=> string(8) "bammyww " }
$aa[0]['followe'] is string(8) "bammyww "
You can also use array_column as
array_column($aa,'followe');//retrieves values associated with the key followe

Object type array elements php

I stored some values in db using json_encode.Now on fetching i got values like this ["ab","cd"].I have tried by exploding,json_encode and then decode.But nothing works.some of tried code is below
$array = "["ab","cd"]";
$value = (array)$array;
//-------------
$array = (array) $array;
// get_object_vars
$array = get_object_vars($object);
print_r($array);
when i loop directly on array i didn't get any values.Thanks for any help in advance.
on this i got like this :
var_dump(json_decode($object));
print_r($object);
OUTPUT :
NULL ["MKD","KD3"]
If I am understanding your question, I think you are looking for json_decode.
$json_encoded_str = '["ab","cd"]';
// Will return an array of elements in your string
var_dump(json_decode($json_encoded_str));
The result would be
array(2) {
[0]=> string(2) "ab"
[1]=> string(2) "cd"
}

Search an array stored in a Session

I pull a list of permissions from a the DB using and put them into an array;
while($row = mysql_fetch_assoc($get_permissions)) {
$_SESSION['permissions'][] = $row;
}
The contents of the session variable then looks like this;
array(2) {
[0]=> array(1) {
["permission_name"] => string(15) "acl_assets_read"
}
[1]=> array(1) {
["permission_name"] => string(16) "acl_assets_write"
}
}
below is the output using print_r instead which makes it easier to read.
Array ( [0] => Array ( [permission_name] => acl_assets_read ) [1] => Array ( [permission_name] => acl_assets_write ) )
I've read about using array_search and think it should work. I've tried to use the following to search for a permission;
if (array_search('acl_assets_read', $_SESSION['permissions'])) {
echo "true";
}
The problem i have is that even though the result is there, it keep returning false. The syntax looks correct to me.
Your problem is that you add the entire row (which is an array of its own) from your database into the $_SESSION['permissions']-array, forming a sub-array for each time it iterates the values from the database.
This means that all values in $_SESSION['permissions'] are arrays, not strings. This in turn means that you cannot search for a string like that.
If you have stored the values you are interested in, in a column named permissions in the database, you simply need to add that element only to your $_SESSION['permissions']-array, like this
$_SESSION['permissions'][] = $row['permissions'];
This will add the string from that row into an element in the array $_SESSION['permissions'].
It's also worth noting that array_search() returns the key of the array, where as the first element will have an index (key) equal to 0. This means that the very first element of your array would really look like if (0) { /* code */ }. This will return to false (if (0) == false), so you should perhaps look into using ìn_array(), which returns a boolean true/false.
if (in_array('acl_assets_read', $_SESSION['permissions'])) {
echo "true";
}
Also, mysql_* functions are deprecated, and you shoud stop using them if you can.
array_search will work for you but you need the proper array to search.
Take a look at this:
$arrOne = array("one", "two");
$arrTwo = array(array("one"), array("two"));
$key = array_search("one", $arrOne);
var_dump($key); // int(0) is the index of where the value was found
$key = array_search("two", $arrTwo);
var_dump($key); // bool(false) because "two" != array("one") or array("two")
Notice that the second array_search will return false because a string does not equal an array.
If you had:
array(2) {
[0]=> string(15) "acl_assets_read"
[1]=> string(16) "acl_assets_write"
}
instead of:
array(2) {
[0]=> array(1) {
["permission_name"] => string(15) "acl_assets_read"
}
[1]=> array(1) {
["permission_name"] => string(16) "acl_assets_write"
}
}
then your array_search would find the proper string
Here is your answer :
$userdb = array(array("permission_name" => 'acl_assets_read'),array("permission_name" => 'acl_assets_write'));
$key = array_search("acl_assets_write", array_column($userdb, 'permission_name'));
if($key != ''){
echo 'true';
}
If needle found $key show key of needle. If needle is not found $key show blank.

How to return id of each array in Session Array?

I am trying to return the ids of each array in my session cart however at the moment it is not working correctly because i am only returning the position of the array which is not working when i go to remove the item from the array.
So how can i return the actual id of the array code below:
Current Array:
$_SESSION['cart'] = array(1) {
[1]=>
array(3) {
["start"]=>
string(18) "name"
["end"]=>
string(19) "name"
["amount"]=>
string(2) "11"
}
}
From the above i am trying to retrieve 1 from [1]=> where later i will use to delete the array using $_SESSION['cart'][$arrayId];
for now i am counting the loops in the array using $i but this is insufficient.
So to reiterate i am trying to return the "[1]" id from [1]=>, unless there is another method that is better i would be all ears :)
Hope this makes sense everyone.
Alex
Addtional info:
Lets say i am inside the loop at the moment, can i somehow call the id from inside the foreach loop?
To iterate over an array's keys and values, use foreach:
foreach ($_SESSION['cart'] as $key => $value) {
if ($value/* something */) {
echo $key;
}
}
array_keys() is what you need.
If you just need the id of a row in the array, you can do the following:
foreach ($_SESSION['cart'] as $id => $array) {
echo $id; // $id will be the value of the keys of the looped array.
}
$ids = array_keys($_SESSION['cart']);

Get value from a array

update
how can I retrieve this value? I need to do that if I will write the value to my database.
array(3) {
[1]=> NULL
[2]=> array(2) {
[123]=>
int(123)
[122]=>
int(0)
}
[3]=> NULL
}
There is something missing in your output. I assume it looks something like:
// var_dump($array);
array(1) {
[0]=>
string(2) "39"
}
so you can access the value with $array[0]. Simple array access.
As arrays are the most important data structure in PHP, you should learn how to deal with them.
Read PHP: Arrays.
Update:
Regarding your update, which value do you want? You have a multidimensional array. This is what you will get:
$array[1] // gives null
$array[2] // gives an array
$array[2][123] // gives the integer 123
$array[2][122] // gives the integer 0
$array[3] // gives null
Maybe you also want (have) to loop over the inner array to get all values:
foreach($array[2] as $key => $value) {
// do something with $key and $value
}
As I said, read the documentation, it contains everything you need to know. Accessing arrays in PHP is not much different than in other programming languages.
The PHP manual contains a lot of examples, it is a pretty could documentation. Use it!
If your array is referenced as $myArray, you can get the string 39 via $myArray[0], i.e., this zeroth item.

Categories