PHP Array key exist - php

I'm working with an API and now i want to check if an array key exists then do something.
With an array i gather data like this:
$pers_payload = array(
'gender' => 'Unknown', //or Male / Female
'first_name' => $_POST['billing_first_name'],
'family_name' => $_POST ['billing_last_name'],
'email' => $_POST['billing_email'],
'linked_as_contact_to_organization' => array(
array(
'organization_id' => $organization_id, // add the person as a contact to the newly created organization
'work_email' => $_POST['billing_email'],
'work_phone' => $_POST['billing_phone']
)
),
'visiting_address' => array(
'country_code' => 'NL'
), // can be extented with other address data
'postal_address' => array(
'country_code' => $_POST['billing_country']
) // can be extented with other address data
);
Then i use a get request like this:
$tet = $SimplicateApi->makeApiCall('GET','/crm/person?q[first_name]=Kevin');
And then i check if the array exists inside the results of the get request like this:
if(array_key_exists('first_name', $tet)) {
// do Nothing
}else{
// make API call
$person = $SimplicateApi->makeApiCall('POST','/crm/person',json_encode($pers_payload));
}
Im sure the get request is working, because i did a var_dump($tet); and i got this result:
array(3) { ["data"]=> array(6) { [0]=> array(18) { ["id"]=> string(39) "person:71cf33fb785433ab66550e5701120079
Well thats part of what i got, i cant post all of it. because it contains sensitive information.
For some reason even if the array_key exists this code still runs:
$person = $SimplicateApi->makeApiCall('POST','/crm/person',json_encode($pers_payload));
--
array(3) { ["value"]=> bool(false) ["id"]=> string(41) "interest:7d3458131ea89afbe1bb3149bee8b668" ["name"]=> string(3) "Web" } } } } ["gender"]=> string(7) "Unknown" ["first_name"]=> string(5) "Kevin" ["family_name"]=> string(7) "A" ["full_name"]=> string(13) "Kevin A" ["email"]=> string(24) "ma#edd-marketingsuppxort.nl" ["phone"]=> string(8) "06269684" } [5]=> array(11) { ["id"]=> string(39) "person:51045f230a9cc39136aaf3a22a069eb0" ["interests"]=> array(1) { [0]=>

What are the first array keys of $tet?
We can see the first one is data, but what about the others one?
if(array_key_exists('first_name', $tet['data'])) {
//code...
}
edit: as #lma says array_key_exists can not dig into child, and even the edited structure you gave us look weird, some trailing } in the middle of the array.

Related

Array into array using array_push key issue

I'm getting confused about how to insert array into array and give it a key name. Not number!.
I have the main array, which contains info about customer. the sub array should be called ["verlauf"].
The ["verlauf"] array conatins multiple arrays ( as same as db row count ). the main idea is that the sub array should be having the key name ["verlauf"]. in my code im getting the [0] as key.
Current array output:
array(19) {
["id"]=> string(1) "1"
["name"]=> string(11) "qwert zuiop"
["email"]=> string(23) "xy#gmail.com"
["phn_num"]=> string(12) "123456789"
[0]=> array(1) {
[0]=> array(4) {
["datum"]=> string(10) "30.07.2020"
["uhr_zeit"]=> string(5) "22:25"
["status"]=> string(1) "0"
["info"]=> string(34) "some info"
}
[1]=> array(4) {
["datum"]=> string(10) "30.07.2020"
["uhr_zeit"]=> string(5) "23:25"
["status"]=> string(1) "1"
["info"]=> string(34) "some info"
}
}
}
what i want is that the [0] on line 6 in the above example to be ["verlauf"]
My PHP:
while ($row = mysqli_fetch_array($result)) {
$verlaufArray[] = array(
"datum" => $row['datum'],
"uhr_zeit" => $row['uhr_zeit'],
"status" => $row['status'],
"info" => $row['info']);
}
array_push($returnArray, $verlaufArray);
Please note that $returnArray is the "main array".
You can simply do that by using associate array-
Your PHP code -
while ($row = mysqli_fetch_array($result)) {
$verlaufArray[] = array(
"datum" => $row['datum'],
"uhr_zeit" => $row['uhr_zeit'],
"status" => $row['status'],
"info" => $row['info']);
}
$returnArray['verlauf'] = $verlaufArray;
There's no need to complicate things so much. It looks like you need just one line of code.
$returnArray['verlauf'] = $result->fetch_all(MYSQLI_ASSOC);
There's no need for the while loop if the structure remains the same. fetch_all(MYSQLI_ASSOC) will give you an array containing associative results from your query.

Grouping array items based on string value

I am trying to group an array by sport. It could be n number of sports. Finally, then create a new array with it. Is there an efficient way to this without going overkill?
$sports = [
['sport' => 'soccer', 'id' => 97487];
['sport' => 'soccer', 'id' => 244800];
['sport' => 'soccer', 'id' => 258740];
['sport' => 'basketball', 'id' => 147884];
['sport' => 'baseball', 'id' => 222240];
['sport' => 'baseball', 'id' => 222245];
];
Initial array:
array(6) {
[0]=>
array(2) {
["sport"]=>
string(6) "soccer"
["id"]=>
int(97487)
}
[1]=>
array(2) {
["sport"]=>
string(6) "soccer"
["id"]=>
int(244800)
}
[2]=>
array(2) {
["sport"]=>
string(6) "soccer"
["id"]=>
int(258740)
}
[3]=>
array(2) {
["sport"]=>
string(10) "basketball"
["id"]=>
int(147884)
}
[4]=>
array(2) {
["sport"]=>
string(8) "baseball"
["id"]=>
int(222240)
}
[5]=>
array(2) {
["sport"]=>
string(8) "baseball"
["id"]=>
int(222245)
}
}
Desired results:
array(3)
{
[0]=>
array(3) {
[0]=>
array(2) {
["sport"]=>
string(6) "soccer"
["id"]=>
int(97487)
}
[1]=>
array(2) {
["sport"]=>
string(6) "soccer"
["id"]=>
int(244800)
}
[2]=>
array(2) {
["sport"]=>
string(6) "soccer"
["id"]=>
int(258740)
}
}
[1]=>
array(1) {
[0]=>
array(2) {
["sport"]=>
string(10) "basketball"
["id"]=>
int(147884)
}
}
[2]=>
array(2) {
[0]=>
array(2) {
["sport"]=>
string(8) "baseball"
["id"]=>
int(222240)
}
[1]=>
array(2) {
["sport"]=>
string(8) "baseball"
["id"]=>
int(222245)
}
}
}
You can group the array like so:
$sports = [
['sport' => 'soccer', 'id' => 97487],
['sport' => 'soccer', 'id' => 244800],
['sport' => 'soccer', 'id' => 258740],
['sport' => 'basketball', 'id' => 147884],
['sport' => 'baseball', 'id' => 222240],
['sport' => 'baseball', 'id' => 222245]
];
// we will build an array here where the key is the sport
// name and the value is an array of objects pertaining
// to that sport i.e. 'basketball' => [bb1, bb2, ...]
$array = array();
// now consider every sport object in your original array
foreach($sports as $key => $item)
{
if (array_key_exists($item['sport'], $array)) {
// we encountered this same sport in the past so we
// know $array['sportName'] already exists and can
// push right to it
$array[$item['sport']][] = $item;
} else {
// we have never seen this sport before and now must
// insert the sport into $array['sportName'] = []
// and push this sport object to it
$array[$item['sport']] = [$item];
}
}
// since $array's keys are the names of the sports themselves, but
// you want the keys to be numeric, this will build a new array
// from just the values of $array which at this point contains
// grouped arrays of sport objects
$result = array_values($array);
// print the results for good measure :)
print_r($result);
This works by looping over your sports array and building a second array of [sportName => arrayOfThatSport]. Inside the for loop, we are checking to see if a given sport already exists in this array. If it does, great, add the sport to the corresponding array for that sport. Otherwise, create a new array for that sport available at $array['sportName'] = [sportObject]. If you consider several iterations of the loop you will see that we're either always adding to an existing $array['sportName'] array, or creating a new array at this position whenever we encounter a new sport we've never seen before. This gives us a final array similar to: [ "sport
: [...], "sport2": [...] ] but in your case you want a numeric array not an associative array, hence the call to array_values.
This is my suggested solution.
$groupedSports = [];
foreach ($sports as $item) {
if (empty($groupedSports[$item['sport']])) {
$groupedSports[$item['sport']] = [];
}
$groupedSports[$item['sport']][] = $item;
}
Short explanation:
line 1: we initialize an empty array
line 2: we start a loop on the original array
line 3-5: if it's the first occurrence for the current sport, we initialize an empty array for that sport (avoid warnings)
line 6: we assign current item to the appropriate array

Create a checkbox for tags in Wordpress

Im editing a plugin because I want to create a checkbox for the tags the plugin has. In this moment Ive got in a variable, this array:
array(9) { [129]=> object(EM_Tag)#84 (15) { ["id"]=> string(3) "129" ["term_id"]=> string(3) "129" ["name"]=> string(35) "Accessible for non-English speakers" ["slug"]=> string(11) "non-english" ["term_group"]=> string(1) "0" ["term_taxonomy_id"]=> string(3) "129" ["taxonomy"]=> string(10) "event-tags" ["description"]=> string(0) "" ["parent"]=> string(1) "0" ["count"]=> string(1) "0" ["fields"]=> array(0) { } ["required_fields"]=> array(0) { } ["feedback_message"]=> string(0) "" ["errors"]=> array(0) { } ["mime_types"]=> array(3) { [1]=> string(3) "gif" [2]=> string(3) "jpg" [3]=> string(3) "png" } } }
There are more tags but I just put one. I would like to generate a checkbox for each tag.
One solution is to iterate over the array that you provided and access the fields that way. I made a shortened array with proper indentation based on your example provided. It seems to be the same but let me know otherwise.
$array = array(
129 => array(
'id' => '129',
'name' => 'Accessible for non-English Speakers'
),
130 => array(
'id' => '130',
'name' => 'A second piece of information'
),
131 => array(
'id' => '131',
'name' => 'A third piece of information'
)
);
// Iterate over the array
foreach ($array as $c) {
// Access the required data
$id = $c['id'];
$name = $c['name'];
// Generate your checkbox
print "<input type='checkbox' name='$name' id='$id'>";
}

Weird data structure returned in find query

I have the following Models with the following relations between them (I just posted the relevant information about them).
Persona.php
public $hasMany = array(
'PersonaHasLdaphost' => array(
'className' => 'PersonaHasLdaphost',
'foreignKey' => 'persona_id'
)
);
Ldaphost.php
public $hasMany = array(
'PersonaHasLdaphost' => array(
'className' => 'PersonaHasLdaphost',
'foreignKey' => '__ldaphosts_id',
'dependent' => false
)
);
PersonaHasLdaphost.php
public $belongsTo = array(
'Persona' => array(
'className' => 'Persona',
'foreignKey' => 'persona_id',
),
'Ldaphost' => array(
'className' => 'Ldaphost',
'foreignKey' => '__ldaphosts_id',
)
);
I have other models, even Persona itself, with this kind of relation working just fine.
But with those ones, when I query the database with a find:
$this->Persona->Behaviors->load('Containable');
$options = array('conditions' => array('Persona.' . $this->Persona->primaryKey => $id),
'contain' => array(
'Personaacceso',
'Personainterna',
'PersonaHasLdaphost' => array('Ldaphost')),
'recursive'=>1);
$persona = $this->Persona->find('first', $options);
I get this weird ouput:
["PersonaHasLdaphost"]=> array(2) {
[0]=> array(4) {
["id"]=> string(3) "154"
["persona_id"]=> string(3) "315"
["Ldaphost"]=> array(0) {}
["PersonaHasLdaphost"]=> array(1) {
[0]=> array(1) {
["__ldaphosts_id"]=> string(2) "41"
}
}
}
[1]=> array(4) {
["id"]=> string(3) "174"
["persona_id"]=> string(3) "315"
["Ldaphost"]=> array(0) {}
["PersonaHasLdaphost"]=> array(1) {
[0]=> array(1) {
["__ldaphosts_id"]=> string(3) "120"
}
}
}
}
When it should be something like:
["PersonaHasLdaphost"]=> array(2) {
[0]=> array(4) {
["id"]=> string(3) "154"
["persona_id"]=> string(3) "315"
["__ldaphosts_id"]=> string(2) "41"
["Ldaphost"]=> array(0) {}
}
...
With data inside "Ldaphost" of course, cause there is an entry in the ldaphost table for those ids.
So can anyone give me a hint why this is happening? I can't see why this one is throwing different results than the others.
I finally managed to solve it.
Seems cakePHP doesn't like dealing with database tables and/or column names starting with double underscore: __ldaphosts table and __ldaphosts_id.
Once I tried with both names modified, my data was returned correctly:
["PersonaHasLdaphost"]=> array(1) {
[0]=> array(4) {
["id"]=> string(3) "165"
["persona_id"]=> string(3) "455"
["ldaphosts_id"]=> string(3) "120"
["Ldaphost"]=> array(8) {
["id"]=> string(3) "120"
["hostname"]=> string(7) "xxxx"
["ip"]=> string(14) "xxx.xx.xxx.xxx"
["mac"]=> string(17) "xx:xx:xx:xx:xx:xx"
["tipo"]=> string(6) "server"
["encendible"]=> bool(false)
["apagable"]=> bool(false)
["descripcion"]=> string(24) "xxxxxxxxxxxxxxxxxxxxxxx"
}
}
}

laravel 4 form submit with multiple input

this is the var_dump($_POST) :
array(18) { ["_token"]=> string(40) "Qg0krYddkI2cnPQBy5T3yGJdQqRBbb9q173MXzoa" ["from_name"]=> string(2) "4r" ["from_address"]=> string(1) "4" ["invoice_id"]=> string(1) "4" ["invoice_date"]=> string(0) "" ["due_date"]=> string(0) "" ["to_name"]=> string(1) "4" ["to_address"]=> string(1) "4" ["item"]=> array(1) { [0]=> string(5) "Hours" } ["desc"]=> array(1) { [0]=> string(2) "44" } ["​unitAmt"]=> array(1) { [0]=> string(1) "4" } ["​qty"]=> array(1) { [0]=> string(1) "4" } ["​amount"]=> array(1) { [0]=> string(2) "16" } ["invoiceNotes"]=> string(2) "44" ["subTotal"]=> string(2) "16" ["total"]=> string(2) "16" ["amtPaid"]=> string(1) "0" ["balDue"]=> string(2) "16" }
As you can see the variable unitAmt is being posted, but I am getting this error when I use it :
ErrorException
Undefined index: unitAmt
open: /var/www/lk/htdocs/app/routes.php
//var_dump($rows);
//var_dump($description);
for($i=0; $i<count($rows);$i++){
DB::table('item_description')->insert(
array('invoice_id' => $returnID, 'item' => $rows[$i], 'description' => $description[$i],
'unit_price' => $_POST['unitAmt'][$i], 'quantity' => $_POST['​qty'][$i], 'amount'=>$_POST['​amount'][$i]));
}
This works fine for qty and amount which are posted similarly. Same thing is happening at other places also on dumping a variable I can see data is there but when I use it shows undefined index.
Edit :
THis is my code in route.php
var_dump($_POST);
$rows = $_POST['item'];
$description = $_POST['desc'];
for($i=0; $i<count($rows);$i++){
DB::table('item_description')->insert(
array('invoice_id' => $returnID, 'item' => $rows[$i], 'description' => $description[$i],
'unit_price' => $_POST['unitAmt'][$i], 'quantity' => $_POST['​qty'][$i], 'amount'=>$_POST['​amount'][$i]));
}
Why are you using Laravel to use standard PHP functions? That kind of insertion code shouldn't be in the routes.php file, it should be in a controller or a closure. You should probably using an Eloquent model to create items. Furthermore, you can use the Input class to retrieve data that is provided by GET or POST parameters.
I recommend you to use Eloquent model to insert an ITEM data like this way and also loop thru for all the items in your result set:-
Use input class to get POST and GET variables in laravel way
Input::get('invoice_id')
method get() - returns the POST and GET vars
method e() - Convert HTML characters to entities and defined in laravel/helper.php
Use Eloquent to add new row in db in laravel way like:-
item_description::create($arr);
A simple example that is adding an item to item_description table in a cleaner Laravel way:-
$arr = array(
'invoice_id' => e(Input::get('invoice_id')),
'item' => e(Input::get('item')),
'description' => e(Input::get('desc')),
'unit_price' => e(Input::get('unitAmt')),
'quantity' => e(Input::get('qty')),
'amount' => e(Input::get('amount')),
);
// Insert Data in table
$item_description= item_description::create($arr);

Categories