PHP radom output from key value array - php

How can I get the follow thing done.
The follow array I have:
array(2) { [0] => array(3) {
["id"] => string(1) "5"
["avatar"] => string(15) "4e0d886ee9ed3_n"
["username"] => string(5) "testuser1"}
[1] => array(3) {
["id"] => string(1) "1"
["avatar"] => string(15) "4e25bc58b6789_w"
["username"] => string(6) "testuser2"
}
}
I want to create a array with just one user in it, but it has to be random. It can be like
user with id=5, id=1 or a hole other user (when there are more users).

Did you try, something like:
$rand = array_rand($your_array);
http://fr2.php.net/manual/en/function.array-rand.php

Try using array_rand().
$randomKey = array_rand($yourArray);
$randomUserId = $yourArray[$randomKey]['id'];
Simple.

$rand_user = array_rand($your_array);
PHP Manual: array_rand

Related

How to split url parameters with ampersand as array

I want to split the parameters sent through URL.
Here is my text.
"mytext=A & B
Company&anothertext=20&texttwo=SampleText&array[1]=10&array[2]=20"
Expected output:
['mytext'=>'A & B Company', 'anothertext'=> 20, 'texttwo' =>
'SampleText', array[1] => 10, array[2] => 20 ].
I tried with explode('&', $params) and parse_str($url_components['query'], $params);
both giving only A as result. I need as 'A & B Company'. How to achieve this?
I think you're looking for parse_str()?
See: https://3v4l.org/L2UZa
The result is:
array(5) {
["mytext"] => string(2) "A "
["B_Company"] => string(0) ""
["anothertext"]=> string(2) "20"
["texttwo"] => string(10) "SampleText"
["array"] => array(2) {
[1] => string(2) "10"
[2] => string(2) "20"
}
}
This differs slight from what you want because of the &. if you could replace the & with the URL encoded version %26 it would work.
See: https://3v4l.org/OXfsD
The result now is:
array(5) {
["mytext"] => string(2) "A & B_Company"
["anothertext"]=> string(2) "20"
["texttwo"] => string(10) "SampleText"
["array"] => array(2) {
[1] => string(2) "10"
[2] => string(2) "20"
}
}
Basically the & is an anomaly, it shouldn't have been there in the first place. URL query parameters should be made with urlencode(), or something equivalent, which would have replace & by %26.

How to store associative array in Laravel

I'm new to Laravel, and I want to store this array in DB.
This is the php code of my array:
$socialNetwork = array();
$socialNetwork[0]["name"]= "Facebook";
$socialNetwork[0]["account"]= "facebook_account";
$socialNetwork[1]["name"]= "Twitter";
$socialNetwork[1]["account"]= "twitter_account";
$socialNetwork[2]["name"]= "Instagram";
$socialNetwork[2]["account"]= "insta_account";
The var_dump() looks like this:
array(3) {
[0] => array(2) {
["name"] => string(8) "Facebook"
["account"] => string(16) "facebook_account"
}
[1] => array(2) {
["name"] => string(7) "Twitter"
["account"] => string(15) "twitter_account"
}
[2] => array(2) {
["name"] => string(9) "Instagram"
["account"] => string(13) "insta_account"
}
}
I've tried several things but I can't get it to work!
Please help with the code. The table name is socialAccounts
Add a column in your database for this field; a JSON or TEXT type will do the job.
Next, you should add the column to the $casts array on your SocialAccount model:
protected $casts = [
'facebook_account' => 'array',
];
Now, whenever you retrieve this value, it will be deserialized for you.
To store the value, just use json_encode():
$social_account->facebook_account = json_encode($facebookArrayData);
$social_account->save();
You can read more on attribute casting in the docs; https://laravel.com/docs/7.x/eloquent-mutators#attribute-casting

Whats the proper way to access the data in a xml object

I am working on a API project where i get an XML Object as a response. The response can contain one or more products in the NewOrder object(below).However when i try to display the info using a foreach loop it breaks if the only has one entry. i guess it is because the index [0] does not exist in the object.how can i through the xml object and display since there is no [0] i the object. OR how do i add the index [0] in the object.
object(stdClass)#49 (1) {
["NewOrder"] => object(stdClass)#50 (12) {
["BTN"] => string(10) "XXXXXXXXXXXXXXXxx"
["PreOrderTransactionId"] => string(22) "XXXXXXXX"
["PartnerOrderId"] => string(17) "XXXXXXXXXXX"
["QwestOrderId"] => string(9) "N57395699"
["SalesCode"] => string(7) "XXXXXXXX"
["OrderStatus"] => string(7) "Pending"
["OrderStatusCode"] => string(4) "OPEN"
["OrderStatusSourceSystem"] => string(5) "CPLUS"
["OrderStatusMessage"] => string(0) ""
["OrderStatusDate"] => string(10) "2013-12-09"
["OrderStatusTime"] => string(8) "08:02:30"
["ProductFamily"] => array(3) {
[0] => object(stdClass)#51 (2) {
["ProductFamilyName"] => string(7) "BUNDLE+"
["ProductLines"] => object(stdClass)#52 (3) {
["WTN"] => string(10) "3033689919"
["AppointmentDate"] => string(10) "2013-12-20"
["Products"] => object(stdClass)#53 (5) {
["ProductName"] => string(36) "INTERNET 100+ MBPS & HOME PHONE PLUS"
["Usoc"] => string(5) "BBBVC"
["Quantity"] => string(1) "1"
["Action"] => string(1) "I"
["Status"] => string(4) "OPEN"
}
}
}
}
}
}
I have tried the following but it didn't work:
if (!is_array($this->Orders->NewOrder)) {
$this->Order->NewOrder = array($this->Orders->NewOrder["NewOrder"]);
}
foreach ($this->Orders->NewOrder as $order){?>
I am getting the following error:
Fatal error: Cannot use object of type stdClass as array in
I think your NewOrder is only an array if it contains more than one object. Use something like this before your loop:
if (!is_array(yourObject["NewOrder"])) {
yourObject["NewOrder"] = array(yourObject["NewOrder"]);
}
The SoapClient has an option that always creates the array, even if here is only one element.
return new SoapClient(
'...',
array(
'location' => '...',
/.../
'features' => SOAP_SINGLE_ELEMENT_ARRAYS
)
);

PHP foreach subarray in array

I'm trying to parse an array that looks like this:
array(1) {
["StrategischeDoelstellingenPerDepartement"] => array(412) {
[0] => array(5) {
["CodeDepartement"] => string(8) "DEPBRAND"
["NummerHoofdstrategischeDoelstelling"] => string(1) "1"
["Nummer"] => string(2) "27"
["Titel"] => string(22) "DSD 01 - HULPVERLENING"
["IdBudgetronde"] => string(1) "2"
}
[1] => array(5) {
["CodeDepartement"] => string(8) "DEPBRAND"
["NummerHoofdstrategischeDoelstelling"] => string(1) "2"
["Nummer"] => string(2) "28"
["Titel"] => string(24) "DSD 02 - Dienstverlening"
["IdBudgetronde"] => string(1) "2"
}
[2] => array(5) {
["CodeDepartement"] => string(8) "DEPBRAND"
["NummerHoofdstrategischeDoelstelling"] => string(1) "2"
["Nummer"] => string(2) "29"
["Titel"] => string(16) "DSD 03 - KLANTEN"
["IdBudgetronde"] => string(1) "2"
}
...
(The array goes on but it's too big to post it here in its entirety)
I can do a foreach loop on the array like this:
foreach($my_arr->StrategischeDoelstellingenPerDepartement as $row){
echo "i found one <br>";
}
However, I want to do the same thing on other arrays and I want to make the function generic. The first key (StrategischeDoelstellingenPerDepartement in this case) can sometimes change, which is why I'd like to do it generically. I've already tried the following:
foreach($my_arr[0] as $row){
echo "i found one <br>";
}
But then I get the following notice, and no data:
Notice: Undefined offset: 0 in C:\Users\Thomas\Documents\GitHub\Backstage\application\controllers\AdminController.php on line 29
This is probably a silly question, but I'm new to PHP and this seemed like the right way to do it. Obviously, it isn't. Can anyone help me out, please?
Use reset to grab the first element of $my_arr without knowing the key name:
$a = reset($my_arr);
foreach($a as $row){
echo "i found one <br>";
}
Shift the sub-array off the main array and loop over it:
$sub = array_shift($my_arr);
foreach ($sub as $row) {
echo $row['Titel'], "<br>";
}
You are trying to do is object, not array $my_arr->StrategischeDoelstellingenPerDepartement.
You could use isset() to check the index existence:
if(isset($my_arr['StrategischeDoelstellingenPerDepartement'])){
foreach($my_arr['StrategischeDoelstellingenPerDepartement'] as $row){
echo "i found one <br>";
}
}
Or, you could use array_values() to ignore the array keys and to make it an index array:
$my_new_arr = array_values($my_arr);
foreach($my_new_arr as $row){
echo "i found one <br>";
}
Use current ref : http://in3.php.net/manual/en/function.current.php
$a = current($my_arr);
foreach($a as $row){
echo "i found one <br>";
}

issues using memberOf clause in ldap query

I'm trying to accomplish something very similar to what this user was doing Here.
I followed the answer, but I could not get it working. Inside the Active directory, my memberOf field looks like this:
CN=$VPN Users,CN=Users,DC=iai,DC=pri,CN=$ITAR,CN=Users,DC=iai,DC=pri,CN=allsubscribers,CN=Users,DC=iai,DC=pri
My Filter that works is:
(&(objectCategory=person)(sAMAccountName=$p_username))
I'm trying to get the following to work:
(&(objectCategory=person)(sAMAccountName=$p_username)(memberOf=CN=$ITAR))
I have tried adding the full DN which is
CN=Users,DC=iai,DC=pri
to my filter as well, but I get:
array(1) { ["count"]=> int(0) }
as my response.
I'm using ldap 3
This is the partial Working authentication code written in php:
$login = ldap_bind( $url, "username#somedomain", $password );
$attributes = array("displayname", "mailnickname");
$filter = "(&(objectCategory=person)(sAMAccountName=$username))";
$result = ldap_search($url, "CN=Users,DC=iai,DC=pri", $filter, $attributes);
$entries = ldap_get_entries($url, $result);
What am I doing wrong?
Code Result From #DaveRandom
First Var dump:
string(49) "(&(objectCategory=person)(sAMAccountName=rmoser))"
array(2) {
["count"] => int(1)
[0] => array(8) {
["displayname"] => array(2) {
["count"] => int(1)
[0] => string(10) "Ryan Moser"
}
[0] => string(11) "displayname"
["memberof"] => array(4) {
["count"] => int(3)
[0] => string(36) "CN=$VPN Users,CN=Users,DC=iai,DC=pri"
[1] => string(31) "CN=$ITAR,CN=Users,DC=iai,DC=pri"
[2] => string(40) "CN=allsubscribers,CN=Users,DC=iai,DC=pri"
}
[1]=> string(8) "memberof"
["mailnickname"] => array(2) {
["count"] => int(1)
[0] => string(6) "rmoser"
}
[2] => string(12) "mailnickname"
["count"] => int(3)
["dn"] => string(36) "CN=Ryan Moser,CN=Users,DC=iai,DC=pri"
}
}
bool(false)
Second var_dump:
string(70) "(&(objectCategory=person)(sAMAccountName=rmoser)(memberof=*CN=$ITAR*))"
array(1) {
["count"] => int(0)
}
LDAP filters look for an exact match.
In order to match CN=$ITAR anywhere in a value, you will need to surround it with the filter wildcard character *.
Try this filter:
(&(objectCategory=person)(sAMAccountName=$p_username)(memberOf=*CN=$ITAR*))
Also don't forget that $ITAR is a valid variable name in PHP, so if you place that filter string in double quotes (which you would need to in order for $p_username to be interpolated) PHP will attempt to interpolate $ITAR as a variable as well, find that it (probably) doesn't exist and the end result will be that it gets stripped from the string.
$filter = "(&(objectCategory=person)(sAMAccountName=$p_username)(memberOf=*CN=\$ITAR*))";
A useful link for any question concerning a dynamic filter built with PHP is this.

Categories