I have a config that contains an object with all the relevant information regarding my system. Part of it lists all of the ranks currently in the system:
return (object) array(
//User Ranks
"Ranks" => (object) array(
"Developer" => (object) array(
//Admin, User, Banned, Deactivated, Pending Moderation, Pending Email Activation
"AccountState" => "Admin",
//Page View Permission
"PagePermissions" => array(
"cadet/dashboard",
"admin/dashboard",
"admin/users"
),
"TaskPermissions" => array(
"BasicUserSearch",
"AdvancedUserSearch",
"GetRanks",
"EditUser"
)
),
"Staff" => (object) array(
"AccountState" => "Admin",
//Page View Permission
"PagePermissions" => array(
"cadet/dashboard",
"admin/dashboard",
"admin/users"
),
"TaskPermissions" => array(
"BasicUserSearch",
"AdvancedUserSearch"
)
)
)
);
What I need to do is turn this object into a simple array to return to an AJAX call. The array must look like:
(
"Developer" => array("AccountState" => "Admin),
"Staff" => array("AccountState" => "Admin)
)
I tried doing this with this code:
public function GetRanks(){
$LstRanks = (array)$this->config->Ranks;
for($i = 0; $i < count($LstRanks); $i++){
$LstRanks[$i] = array_column($LstRanks[$i], "AccountState");
}
return json_encode(["data" => 0, "ranks" => $LstRanks]);
}
However, the first line of the function returns null resulting in the loop constantly looping and producing errors. What is the best way to cut the object down like shown?
Error
[30-Apr-2017 18:38:47 UTC] PHP Notice: Undefined offset: 0 in /home/thomassm/public_html/php/lib/UserSystem.php on line 23
[30-Apr-2017 18:38:47 UTC] PHP Warning: array_column() expects parameter 1 to be array, null given in /home/thomassm/public_html/php/lib/UserSystem.php on line 23
public function GetRanks(){
$Ranks = (array) $this->config->Ranks;
$LstRanks = array();
foreach($Ranks as $StrRank => $LstRankInfo){
$LstRanks[$StrRank] = $LstRankInfo->AccountState;
}
return json_encode(["data" => 0, "ranks" => $LstRanks]);
}
This is my solution using the advice from the comments. It seems that I was incorrectly turning the object into an array.
Related
I am making my own array from another one, using email field as key value. If there is more results with same email I am amking array_push to existing key.
I am getting always data in my array (with email) and here is the example
Input data
Example data
$saved_data = [
0 => ['custom_product_email' => 'test#test.com',...],
1 => ['custom_product_email' => 'test#test.com',...],
2 => ['custom_product_email' => 'bla#test.com',...],
3 => ['custom_product_email' => 'bla#test.com',...],
...
];
Code
$data = [];
foreach ($saved_data as $products) {
$curVal = $data[$products->custom_product_email];
if (!isset($curVal)) {
$data[$products->custom_product_email] = [];
}
array_push($data[$products->custom_product_email], $products);
}
Error
I am getting error Undefined index: test#test.com and if I debug my array, there is key with value of 'test#test.com', so key is defined (!)
so var $curVal key is undefined
Result
So the goal of foreach is to filter all objects in array with same email, here is the example:
$data = [
'test#test.com' => [
0 => {data},
1 => {data},
...
],
'bla#test.com' => [
0 => {data},
1 => {data},
...
],
];
this line $curVal = $data[$products->custom_product_email]; is useless and is the one provoking the error: you just initialized $data as an empty array, logically the index is undefined.
You should test directly if (!isset($data[$products->custom_product_email])) {
Then explanation: there is a fundamental difference between retreiving the value of an array's index which is undefined and the same code in an isset. The latter evaluating the existence of a variable, you can put inside something that doesn't exist (like an undefined array index access). But you can't store it in a variable before the test.
Did you not see the error message?
Parse error: syntax error, unexpected '{' in ..... from this code
$saved_data = [
0 => {'custom_product_email' => 'test#test.com',...},
1 => {'custom_product_email' => 'test#test.com',...},
2 => {'custom_product_email' => 'bla#test.com',...},
3 => {'custom_product_email' => 'bla#test.com',...},
...
];
Change the {} to [] to correctly generate the array.
$saved_data = [
0 => ['custom_product_email' => 'test#test.com',...],
1 => ['custom_product_email' => 'test#test.com',...],
2 => ['custom_product_email' => 'bla#test.com',...],
3 => ['custom_product_email' => 'bla#test.com',...],
...
];
Your next issue is in this code
$data = [];
foreach ($saved_data as $products) {
$curVal = $data[$products->custom_product_email];
// ^^^^^
$data is an empty array that you initialised 2 lines above, so it does not contain any keys or data!
Check, if $data[$products->custom_product_email] is already set in $data array
Try This code
$data = [];
foreach ($saved_data as $products) {
$curVal = isset($data[$products->custom_product_email]) ? $data[$products->custom_product_email] : null;
if (!isset($curVal)) {
$data[$products->custom_product_email] = [];
}
array_push($data[$products->custom_product_email], $products);
}
Trying to make $emo_word a global variable so I can call it in another function. But whenever I put global $emo_word, it gives me the error below. If I remove global, it is OK, but I want to call the global, what can I do?
Warning: Illegal string offset 'cat_id' in /home2/898992on708/public_html/mysitel.com/wp-content/plugins/gallery/gallery.php on line 212
<?php
function name_1(){
global $emo_word;
$emo_word = array(
1 => array(
'word' => 'LOL !',
'id_name' => 'lol',
'cat_id' => '1'
),
2 => array(
'word' => 'COOL !',
'id_name' => 'cool',
'cat_id' => '2'
)
);
foreach($emo_word as $word){
$word['cat_id'];
}
}
?>
Your code is valid but the error is telling you that there is a value in $emo_word that isn't an array but is instead a string.
If you were to run var_dump($emo_word); where you get that error you will see.
Essentially when you are accessing the cat_id index something like this is happening:
$emo_word = array(
1 => array('cat_id' => 1, 'word' => 'LOL'),
2 => 'string',
);
In the loop when it evaluates $word['cat_id'] on the string value it throws the warning Illegal string offset.
Check your array to make sure it is contains what you expect.
I have this php array $result2 that looks like this.
[
(int) 0 => object(stdClass) {
id => (int) 1
username => 'asd'
password => '123'
fullname => 'asd'
email_addr => 'asd#gmail.com'
}
]
From $result2, I want to have a $json_result that looks like this;
[{"email_addr":"asd#gmail.com"}]
I tried
$emailAddress[] = ['email_addr' => $result2['email_addr'] ];
echo json_encode($emailAddress);
However, the error I get is this;
Notice (8): Undefined index: email_addr
[APP/Controller\DeptUsersController.php, line 126]
The output is like this which is wrong;
[{"email_addr":null}]
What is the correct way?
Read carefully (int) 0 => object(stdClass) It's an object, and this object is an element with index 0 of an array. So:
$emailAddress[] = ['email_addr' => $result2[0]->email_addr ];
it's object you can't show value if using $result2['email_addr'] you should using this $result2->email_addr method
You have an object of type stdClass so you can't access directly to the field email_addr. Try this code:
$mObject = new stdClass();
$mObject = $result2[0];
$emailAddress[] = ['email_addr' => $mObject->email_addr ];
echo json_encode($emailAddress);
This should fix your error
Try this:
$emailAddress[] = ['email_addr' => $result2[0]->email_addr ];
You can use array_intersect_key :
$wanted = ["email_addr"=>""];
$data = [
"id" => 1,
"username" => 'asd',
"password" => '123',
"fullname" => 'asd',
"email_addr" => 'asd#gmail.com',
];
$result = array_intersect_key($wanted, $data);
var_dump($result);
It useful when you need one or more key to find. It more saving time
I'm trying to build an archive-class for my firebird database. And I have the following problem a couple of times already:
I want to construct an array-structure like that:
/**
* #var [] stores the success log of all db operations
*
* $_log = Array(
* (string) [DATA_SOURCE] => Array(
* (int) [0] => Array(
* (string) [id] => (int) 32,
* (string) [action] => (string) "update/insert/delete",
* (string) [state] => (int) 1,
* (string) [message] => (string) "success/error",
* )
* )
* )
*/
private $_log = array();
MY 1. TRY:
// push result to log array
array_push(
$this->_log,
array(
"archive" => array(
"id" => $row["ID"],
"action" => "update",
"state" => $success,
),
)
);
RESULTS IN:
Array(
[0] => Array(
[archive] => Array(
[id] => 32
[action] => update
[state] => 1
)
)
)
That's not exactly what i want. I want the "data-source"-key here "archive" in front of the pushed entry [0].
MY 2nd TRY
array_push(
$this->_log["archive"],
array(
"id" => $row["ID"],
"action" => "update",
"state" => $success,
)
);
RESULTS IN
<br />
<b>Warning</b>: array_push() expects parameter 1 to be array, null given in <b>/Users/rsteinmann/web/intranet/pages/firebird/ArchiveTables.php</b> on line <b>238</b><br />
I'm a bit helpless with this task. I also tried to find anything on google or stackoverflow but there was nothing really useful.
I would be so glad if someone could help me with that!
Thank you,
Raphael
$this->log['archive'][] = array('id' => ...);
This is the sanest way to do it. PHP will create any non-existing keys (like archive) for you. array_push on the other hand is a function call and requires its arguments to already exist, it can't create a non-existing archive key for you. You'd have to do that before you call the function.
array_push is mostly useful if you need to push several arguments at once (array_push($arr, $a, $b, $c)), otherwise $arr[] = $a is the generally preferred and officially recommended syntax.
I would like to retrieve the first key from this multi-dimensional array.
Array
(
[User] => Array
(
[id] => 2
[firstname] => first
[lastname] => last
[phone] => 123-1456
[email] =>
[website] =>
[group_id] => 1
[company_id] => 1
)
)
This array is stored in $this->data.
Right now I am using key($this->data) which retrieves 'User' as it should but this doesn't feel like the correct way to reach the result.
Are there any other ways to retrieve this result?
Thanks
There are other ways of doing it but nothing as quick and as short as using key(). Every other usage is for getting all keys. For example, all of these will return the first key in an array:
$keys=array_keys($this->data);
echo $keys[0]; //prints first key
foreach ($this->data as $key => $value)
{
echo $key;
break;
}
As you can see both are sloppy.
If you want a oneliner, but you want to protect yourself from accidentally getting the wrong key if the iterator is not on the first element, try this:
reset($this->data);
reset():
reset() rewinds array 's internal
pointer to the first element and
returns the value of the first array
element.
But what you're doing looks fine to me. There is a function that does exactly what you want in one line; what else could you want?
Use this (PHP 5.5+):
echo reset(array_column($this->data, 'id'));
I had a similar problem to solve and was pleased to find this post. However, the solutions provided only works for 2 levels and do not work for a multi-dimensional array with any number of levels. I needed a solution that could work for an array with any dimension and could find the first keys of each level.
After a bit of work I found a solution that may be useful to someone else and therefore I included my solution as part of this post.
Here is a sample start array:
$myArray = array(
'referrer' => array(
'week' => array(
'201901' => array(
'Internal' => array(
'page' => array(
'number' => 201,
'visits' => 5
)
),
'External' => array(
'page' => array(
'number' => 121,
'visits' => 1
)
),
),
'201902' => array(
'Social' => array(
'page' => array(
'number' => 921,
'visits' => 100
)
),
'External' => array(
'page' => array(
'number' => 88,
'visits' => 4
)
),
)
)
)
);
As this function needs to display all the fist keys whatever the dimension of the array, this suggested a recursive function and my function looks like this:
function getFirstKeys($arr){
$keys = '';
reset($arr);
$key = key($arr);
$arr1 = $arr[$key];
if (is_array($arr1)){
$keys .= $key . '|'. getFirstKeys($arr1);
} else {
$keys = $key;
}
return $keys;
}
When the function is called using the code:
$xx = getFirstKeys($myArray);
echo '<h4>Get First Keys</h4>';
echo '<li>The keys are: '.$xx.'</li>';
the output is:
Get First Keys
The keys are: referrer|week|201901|Internal|page|number
I hope this saves someone a bit of time should they encounter a similar problem.