PHP Display Array with Array_Slice - arrays

$array = array(
'name' => 'john',
'age' => '25',
'birthday' => '02-03-1988',
'gender' => 'male',
'telephone' => '98676878',
'location' => 'Australia'
);
$array_slice = array_slice($array, 0, 3);
foreach($array_slice as $key => $val) {
if($key !== 'age') {
echo $key.' => '.$val.'<br>';
}
}
Output:
name => john
birthday => 02-03-1988
How to display 3 values of array?
So, I want output to be like this:
name => john
birthday => 02-03-1988
gender => male
I am very beginner in programmer, thanks for help.

Update: new solution after exchanging some comments below
You must filter the array and get the result in a new array. Then you display the content of the second array.
To filter your original array, use either array_intersect_key or array_filter functions.

Related

Array to DB::insert()->values(), which is in different order with the columns

Hi folks! I'm trying to transfer data as array from the controller to the model, and then paste the data into the query builder, but the data must be in the same order as specified in the columns.
What options do I have?
And do you think this is a bad practice?
Controller:
$responseNotes = Model::factory('Notes')-> createTicket([
'description' => htmlspecialchars($_POST['description']),
'contact_id' => $_POST['contact_id'],
'pref_contact' => $_POST['pref_contact'],
'dog_id' => $_POST['document_id'],
'type' => $_POST['type'],
'owner_id' => Auth::instance()->get_user()->id,
'cc' => $_POST['cc-emails'],
'title' => $_POST['title']
]);
Model:
public function createNote(array $data)
{
$columns = [
'type',
'owner_id',
'cc',
'title',
'description',
'contact_id',
'pref_contact',
'dog_id'
];
if (!array_diff($columns, array_keys($data))) {
// All needed values exists
$result = DB::insert($this->NOTES, $columns)-> values($data)-> execute($this->SCHEMA);
}
return ($result) ? $result : false ;
}
Thanks to this answer. Solved this by:
// Order $data array according to $column.values
$orderedData = [];
foreach ($columns as $key) {
$orderedData[$key] = $data[$key];
}
$result = DB::insert($this->TICKETS, $columns)
-> values($orderedData)
-> execute($this->SCHEMA);
Why you don't use ORM Model?
in controller:
$responseNotes = ORM::factory('Notes')-> values([
'description' => htmlspecialchars($_POST['description']),
'contact_id' => $_POST['contact_id'],
'pref_contact' => $_POST['pref_contact'],
'dog_id' => $_POST['document_id'],
'type' => $_POST['type'],
'owner_id' => Auth::instance()->get_user()->id,
'cc' => $_POST['cc-emails'],
'title' => $_POST['title']
])
try{
$responseNotes->save();
} catch (ORM_Validation_Exception $ex) {
print_r($ex->errors('models'));
}
And don't use htmlspecialchars($_POST['description'])
In model class modify function (doc):
public function filters()
{
return array(
'description' => array( array('htmlspecialchars') ),
);
}
It looks like You have associative array with structure db_column=>value right? Than You can simply insert like this:
DB::Insert('table_name',array_keys($data))->values(array_values($data))->execute();

Perl: Filter AoH output

I'm trying to sort my AoH which looks like this:
$VAR1 = [
{
'Name' => 'John',
'Lastname' => 'Derp',
'Organization' => 'Finance',
'OfficeNR' => '23',
'ID' => '145'
},
{
'Name' => 'Kate',
'Lastname' => 'Herp',
'Organization' => 'HR',
'OfficeNR' => '78',
'ID' => '35'
},
{
'Name' => 'Jack',
'Lastname' => 'Serp',
'Organization' => 'Finance',
'OfficeNR' => '23',
'ID' => '98'
}
];
What I'm trying to do is to filter my output using keys from AoH, for example print out only those who have 'Organization' => 'Finance'.
I've tried to solve it using new array:
my #SortedAoH = sort { {Organization=>{'Finance'}} } #AoH;
But it doesn't work.
What you want is grep, not sort. You are getting the basic syntax of equivalence checking wrong as well.
Anyway, the filter is:
my #finance_orgs = grep { $_->{'Organization'} eq 'Finance' } #AoH;
The #finance_orgs variable will now only include the ones with Organization set to Finance.
Just an explanation of the pieces:
The $_ variable is the variable that gets assigned whenever the value is implied in a block, such as in grep or map or in a for loop without an explicitly named variable.
$_->{'Organization'} performs a hash lookup on the hash as it iterates through each entry in your array.
eq is the operator used to test for string equivalence (as opposed to == which tests for numeric equivalence).

Directly access value based on another value in anonymous array of hashes

Given the following anonymous array of hashes:
$AoH = [
{
'FORM_FIELD_ID' => '10353',
'VISIBLE_BY' => '10354',
'FIELD_LABEL' => 'ISINCIDENT',
'VALUE' => '',
'DEFAULT_FIELD_LABEL' => 'Yes No',
'FORM_ID' => '2113',
},
{
'FORM_FIELD_ID' => '10354',
'VISIBLE_BY' => '0',
'FIELD_LABEL' => 'CATEGORY',
'VALUE' => 'zOS Logical Security (RACF)',
'DEFAULT_FIELD_LABEL' => 'CATEGORY',
'FORM_ID' => '2113',
},
{
'FORM_FIELD_ID' => '10368',
'VISIBLE_BY' => '10354',
'FIELD_LABEL' => 'STARTDATE',
'VALUE' => '',
'DEFAULT_FIELD_LABEL' => 'REQTYPE',
'FORM_ID' => '2113',
}
];
How would I directly access the FIELD_LABEL value given that I knew the FORM_FIELD_ID is 10353?
I know I can loop through #$AoH and conditionally find $_->{FIELD_LABEL} based on $_->{FORM_FIELD_ID} == 10353, but is there anyway to directly access the wanted value if one of the other values in the same hash is known?
No, not unless you change your data structure. You could e.g. index the records by their form field id:
my %by_form_field_id = map { $_->{FORM_FIELD_ID} => $_ } #$AoH;
Then:
my $field_label = $by_form_field_id{10353}{FIELD_LABEL};
Without changing the data structure, you really have to grep:
my $field_label = (grep { $_->{FORM_FIELD_ID} == 10353 } #$AoH)[0]->{FIELD_LABEL};
You'd have to write a function loop through #array and examine the %hash or maybe use the builtin grep method:
say $_->{FIELD_LABEL} for (grep { $_->{FORM_FIELD_ID} == 10353 } #$AoH )
works. And so does this:
say %$_->{FIELD_LABEL} for (grep { $_->{FORM_FIELD_ID} == 10353 } #$AoH )
but it gives a Using a hash as a reference is deprecated warning (with pumpkin perl-5.16.3).

php multidimensional array as name value pair

For ecommerce, that expected name value pair I have the following approved code:
function create_example_purchase() {
set_credentials();
$purchase = array(
'name' => 'Digital Good Purchase Example',
'description' => 'Example Digital Good Purchase',
'amount' => '12.00', // sum of all item_amount
'items' => array(
array( // First item
'item_name' => 'First item name',
'item_description' => 'a description of the 1st item',
'item_amount' => '6.00',
'item_tax' => '0.00',
'item_quantity' => 1,
'item_number' => 'XF100',
),
array( // Second item
'item_name' => 'Second Item',
'item_description' => 'a description of the 2nd item',
'item_amount' => '3.00',
'item_tax' => '0.00',
'item_quantity' => 2,
'item_number' => 'XJ100',
),
)
);
return new Purchase( $purchase);
}
I would like to get $items Array inside associative $purchase array dynamically from shipping cart.
Is there a way to generate exactly the same output above?
My dirty solution, to write $purchase array as string inclusive the generated $items array in a file and include it
later in the called script.
Help appreciated.
$itemsArray = function_that_returns_your_2d_item_array();
$purchase['items'] = $itemsArray;
or if the function_that_returns_your_2d_item_array() returns a 2d array indexed by 'items' you could do:
$purchase = array_merge($purchase, $itemsArray);

PHP How to order an array in ABC Order from a value of 1 of it's bounds

Ok, I have an array like so:
$my_array = array(
'hi' => array('description' => 'how are you?', 'title' => 'Hello', 'link' => 'http://mylink.com'),
'bye' => array('description' => array('Goodbye!', 'see ya'), 'title' => 'See Ya Later', 'link' => 'http://mybyelink.com'),
'not_now' => array('description' => array('I am away now!', 'gone'), 'title' => 'Away', 'link' => 'http://myawaylink.com'),
'back' => array('description' => array('I am back now!', 'back', 'present'), 'title' => 'Here', 'link' => 'http://mybacklink.com'),
);
So I would like the array to be ordered, within php code, somehow so that it orders it by the TITLE of each array bound: $my_array['hi']['title'], $my_array['bye']['title'], $my_array['not_now']['title'], and $my_array['back']['title'], but it MUST keep the array intact so that all of the values within the hi, bye, not_now, and back are the exact same and all of the arrays (if any are in it, are also the same).
So this array will need to be ordered in ABC order depending on the title, so should return in this order:
$my_array = array(
'not_now' => array('description' => array('I am away now!', 'gone'), 'title' => 'Away', 'link' => 'http://myawaylink.com'),
'hi' => array('description' => 'how are you?', 'title' => 'Hello', 'link' => 'http://mylink.com'),
'back' => array('description' => array('I am back now!', 'back', 'present'), 'title' => 'Here', 'link' => 'http://mybacklink.com'),
'bye' => array('description' => array('Goodbye!', 'see ya'), 'title' => 'See Ya Later', 'link' => 'http://mybyelink.com'),
);
Titles are in ABC order here: Away, Hello, Here, and See Ya Later.
How can I do this and still keep the array intact with all of the sub-arrays in it also?
Thanks guys :)
You want to use the uasort function with a user-defined sort function using strnatcmp in the function. Here is an example for your code:
function titleSort($a, $b) {
return strnatcmp($a['title'], $b['title']);
}
uasort($my_array, 'titleSort');
If desired you could add some sanity checking on the input variables to make sure they are arrays by using is_array.

Resources