Access element in array(array(array(...))) - php

I am having the following array with test data:
'team' =>
array (
0 =>
array (
'firstName' => 'adfadsf',
'lastName' => 'asdfadsfa',
'twitter' => 'ddasfasdf',
),
1 =>
array (
'firstName' => 'adf',
'lastName' => 'asd',
'twitter' => 'www.twitter.com/dfs',
),
2 =>
array (
'firstName' => 'asd',
'lastName' => 'adf',
'twitter' => 'www.twitter.com/adf',
),
3 =>
array (
'firstName' => 'test',
'lastName' => 'test',
'twitter' => 'www.twitter.com/test',
),
),
I would like to access the attributes firstName and lastName.
I tried the following, where $request has as one attribute the team array:
foreach ($request as $key => $value) {
Log::info($key);
$team = new Team();
$team->firstname = $request->team[$key]['firstName'];
$team->lastname = $request->team[$key]['lastName'];
$team->twitter = $request->team[$key]['twitter'];
$team->revisions_id = $revision->id;
Log::info("team");
Log::info($team);
$team->save();
}
Any suggestions how to access the two attributes firstName and lastName?
I appreciate your replies!

As it is not completely clear what's in $request, but I suggest this:
foreach ($request as $key => $value) {
Log::info($key);
if ($key == 'team') {
foreach ($value as $ar_team) {
$team = new Team();
$team->firstname = $ar_team['firstName'];
$team->lastname = $ar_team['lastName'];
$team->twitter = $ar_team['twitter'];
$team->revisions_id = $revision->id;
Log::info("team");
Log::info($team);
$team->save();
}
}
}
Or simply (if other items in $request are not used in foreach):
foreach ($request['team'] as $ar_team) {
$team = new Team();
$team->firstname = $ar_team['firstName'];
$team->lastname = $ar_team['lastName'];
$team->twitter = $ar_team['twitter'];
$team->revisions_id = $revision->id;
Log::info("team");
Log::info($team);
$team->save();
}

looking to your data sample
you should iterate over $request['team'] and accessing to $value for obtain firstName and lastname....
foreach ($request['team'] as $key => $value) {
Log::info($key);
$team = new Team();
$team->firstname = $value['firstName'];
$team->lastname = $value['lastName'];
$team->twitter = $value['twitter'];
$team->revisions_id = $revision->id;
Log::info("team");
Log::info($team);
$team->save();
}

Related

Make this as a dimensional array

I have a problem of making a dimensional array, please help me im using php, this is my scenario
$arrayname = array["john","mell","ben","henz","len"];
$arrayage = array["10","15","58","12","13"];
$arraygender = array["male","female","male","male","female"];
I want to make it like
$arrayidentify = array['name' => 'john', 'age' => '10', 'gender' => 'male'];
And so on,
Please help thanks a lot
class Person {
public $name = "pname";
public $age = "21";
public $gender = "MaleOrFemale";
function __construct($name,$age,$gender){
$this->name = $name;
$this->age = $age;
$this->gender = $gender;
}
}
you can use OOP methods and create an object to store the data of a person and create an array of persons
example
$steve = new Person("Steve Jobs","60","Male");
this'll create a person object $steve with name steve , age 60 , gender Male
you can create may person objects as you wish and put it on an array
$jeff = new Person("Jeff Bezos","50","Male");
$bill = new Person("Bill Gates","64","Male");
put all the above in an array as shown below
$persons = array($steve,$jeff,$bill);
try the below code self study and understand it i have used objects and constructor functions learn about them in w3schools.com
<?php
class Person {
public $name = "pname";
public $age = "21";
public $gender = "MaleOrFemale";
function __construct($name,$age,$gender){
$this->name = $name;
$this->age = $age;
$this->gender = $gender;
}
}
$steve = new Person("Steve Jobs","60","Male");
$jeff = new Person("Jeff Bezos","50","Male");
$bill = new Person("Bill Gates","64","Male");
$persons = array($steve,$jeff,$bill);
foreach($persons as $person){
echo"Person Name : ".$person->name."<br>";
echo"Person Age : ".$person->age."<br>";
echo"Person Gender : ".$person->gender."<br><br>";
}
?>
I think that the array_map solution provided by #ajay-kumar is the best,
I will propose a solution more dynamic and easer to read
function bindDatas(&$resultSolution, $inputData, $keyName)
{
foreach ($inputData as $key => $value) {
$resultSolution[$key][$keyName] = $value;
}
}
the test code some think like this:
//your code here
bindDatas($resultSolution, $arrayname, 'name');
bindDatas($resultSolution, $arrayage, 'age');
bindDatas($resultSolution, $arraygender, 'gender');
echo '<pre>';
print_r($resultSolution);
echo '</pre>';
it's true thar $key variable refer to position in the $inputData, but we an use it here because we want to keep the order in the global array
A simple loop will do here:
<?php
$names = ["john","mell","ben","henz","len"];
$ages = ["10","15","58","12","13"];
$genders = ["male","female","male","male","female"];
for($i=0, $c=count($names), $out=[]; $i<$c; $i++) {
$out[] = [
'name' => $names[$i],
'age' => $ages[$i],
'gender' => $genders[$i]
];
}
var_export($out);
Output:
array (
0 =>
array (
'name' => 'john',
'age' => '10',
'gender' => 'male',
),
1 =>
array (
'name' => 'mell',
'age' => '15',
'gender' => 'female',
),
2 =>
array (
'name' => 'ben',
'age' => '58',
'gender' => 'male',
),
3 =>
array (
'name' => 'henz',
'age' => '12',
'gender' => 'male',
),
4 =>
array (
'name' => 'len',
'age' => '13',
'gender' => 'female',
),
)
You could swap the for loop for a foreach:
foreach ($names as $k => $v) {
$out[] = [
'name' => $names[$k],
'age' => $ages[$k],
'gender' => $genders[$k]
];
}

How to save two array list in one single row in table

How to save two array list in a single row in table?
I have try to foreach every array but I just want to know how to save the array in single row in table just see the picture below. i don't want to have an null value. because this function is like single file that reference in job_orders.
$date = $request->get('date');
$client_name = $request->get('client_name');
$address = $request->get('address');
$service_date = $request->get('service_date');
$service_time = $request->get('service_time');
$contact_person = $request->get('contact_person');
$vehicle = $request->get('vehicles');
$services = $request->input('services');
$supplies = $request->input('supplies');
$accessories = $request->input('accessories');
$miscellaneous = $request->input('miscellaneous');
DB::begintransaction();
try{
$data = [
'vehicle_id' => $request->get('vehicle_id'),
'service_date' => $request->get('service_date'),
'service_time' => $request->get('service_time'),
'discount' => $request->get('discount'),
'total' => $request->get('total'),
'technician' => $request->get('technician'),
'assistant' => $request->get('assistant'),
];
$joborders = $this->joborders->create($data);
if($services !== null){
foreach($services as $service) {
$data = [
'job_order_id' => $joborders->id,
'service_name' => $service['service_name'],
'service_qty' => $service['service_qty'],
'service_cost' => $service['service_cost'],
];
$this->items->create($data);
}
}
if($supplies !== null ){
foreach($supplies as $supply){
$data = [
'job_order_id' => $joborders->id,
'supply_name' => $supply['supply_name'],
'supply_qty' => $supply['supply_qty'],
'supply_cost' => $supply['supply_cost'],
];
$this->items->create($data);
}
}
if($accessories !== null){
foreach($accessories as $accessory){
$data = [
'job_order_id' => $joborders->id,
'accessory_name' => $accessory['accessory_name'],
'accessory_qty' => $accessory['accessory_qty'],
'accessory_cost' => $accessory['accessory_cost'],
];
$this->items->create($data);
}
}
if($miscellaneous !== null)
{
foreach($miscellaneous as $misc){
$data = [
'job_order_id' => $joborders->id,
'misc_name' => $misc['miscellaneous_name'],
'misc_qty' => $misc['miscellaneous_qty'],
'misc_cost' => $misc['miscellaneous_cost'],
];
$this->items->create($data);
}
}

PHP remove array if subarray empty

my array image just like this, if subarray "name" is empty or null i want delete array, how to do that ?
here my current script
$data = array();
$fixedData = array();
$countyName = array();
$numrow = 2;
echo "<pre>";
// insert to tb participant => 1
foreach($sheet as $key => $row){
$data[] = array(
'name' => $this->split_name($row['B']),
'phone' => $row['D'],
'mobile' => $row['E'],
'institution' => $row['F'],
'departement' => $row['G'],
'address' => $row['H'],
'country' => $row['I'],
);
$numrow++;
}
unset($data[0]); //delete first row
$data = array_values($data);
//loop search data
var_dump ($data);
die();
Assume that you have the following data set,
$array = [
[
'name' => 'not null', 'phone' => 12546
],[
'name' => '', 'phone' => 852147
],[
'name' => null, 'phone' => 96325874
],[
'name' => 'have value', 'phone' => 12546
],
];
You can filter the nulled or empty values like several ways :
1-
foreach ($array as $key => &$value) {
if (empty($value['name']) || is_null($value['name'])) {
$value = null;
}
}
$array = array_filter($array);
2-
$newData = [];
foreach ($array as $key => $value) {
if (!empty($value['name']) && !is_null($value['name'])) {
$newData[] = $value;
}
}
3- using array_walk
$newData = [];
array_walk($array, function ($value, $key) use (&$newData) {
if (!empty($value['name']) && !is_null($value['name'])) {
$newData[] = $value;
}
});
4- using array_filter
$newData = array_filter($array, function ($value) {
if (!empty($value['name']) && !is_null($value['name'])) {
return $value;
}
});
<?php
$data = array();
$fixedData = array();
$countyName = array();
$numrow = 2;
echo "<pre>";
// insert to tb participant => 1
foreach($sheet as $key => $row){
if($this->split_name($row['B'])!=='' && $this->split_name($row['B'])!==NULL){
$data[] = array(
'name' => $this->split_name($row['B']),
'phone' => $row['D'],
'mobile' => $row['E'],
'institution' => $row['F'],
'departement' => $row['G'],
'address' => $row['H'],
'country' => $row['I'],
);
$numrow++;
}
}
//loop search data
var_dump ($data);
die();
I simple put an if condition inside your loop so you can check if your value is null or empty and if it is then you don't fill your new array. Also moved your counter inside the if so you increment it only in a success array push
A more "elegant" way for your if condition is this as well:
if (!empty($this->split_name($row['B'])) && !is_null($this->split_name($row['B'])))

Looping through results of a sql query

I have a query that returns multiple rows. I can't seem to find a way to store the rows in the $params array. Is there a way to loop throw and store each row in the $params variable
$aResult = $db->exec_sql($sql);
$params = array(
// where $aResult[o]'' would be row 1 [1] row 2 etc. //
'store_id' => $aResult[]['iStoreID'],
'user_id' => $aResult[]['iUserID'],
'store_name' => $aResult[]['cStoreName'],
'store_url' => $aResult[]['cStoreURL'],
'rid' => $aResult[]['cRID'],
'affiliate_id' => $aResult[]['iAffiliateID'],
'team_id' => $aResult[]['iTeamID'],
'bizOP' => $aResult[]['cDefaultBizOpp'],
'showBizOPp' => $aResult[]['iShowBizOppDropdown'],
'boPosting' => $aResult[]['iEnableBOPosting'],
'brandinglevel' => $aResult[]['iBrandingLevel']
);
thank you for your help
As simple as that:
$params = array();
foreach($aResult as $row) {
$params[] = array(
'store_id' => $row['iStoreID'],
'user_id' => $row['iUserID'],
'store_name' => $row['cStoreName'],
'store_url' => $row['cStoreURL'],
'rid' => $row['cRID'],
'affiliate_id' => $row['iAffiliateID'],
'team_id' => $row['iTeamID'],
'bizOP' => $row['cDefaultBizOpp'],
'showBizOPp' => $row['iShowBizOppDropdown'],
'boPosting' => $row['iEnableBOPosting'],
'brandinglevel' => $row['iBrandingLevel']
);
}
Without knowing the exact structure of the result array i guess you need something like this:
<?php
$params = array();
$mapping = array(
'store_id' => 'iStoredID',
'user_id' => 'iUserID',
// and so on...
);
foreach ($aResult as $row) {
$tempRow = array();
foreach ($row as $key => $value) {
$paramKey = isset($mapping[$key]) ? $mapping[$key] : $key;
$tempRow[$paramKey] = $value;
}
$params[] = $tempRow;
}
I use it like this
$aResult = mysql_query($sql);
while($data = mysql_fetch_array($result)) {
'store_id' = $aResult['iStoreID'];
}
At least that is the idea

Highlight duplicate values in a multidimensional array

I'm outputting a list of purchases, and I want to automatically highlight the presence of duplicate orders.
Here's what the array looks like. The first two orders are duplicate orders place by mistake. You'll notice that the orderid for each is different, while the email and userid remain the same. So the duplication will need to match on email and / or userid, but not on orderid.
array
0 =>
array
'orderid' => string '2009091008261662'
'email' => string 'john#example.com'
'userid' => string '53'
array
1 =>
array
'orderid' => string '2009091008261048'
'email' => string 'john#example.com'
'userid' => string '53'
array
2 =>
array
'orderid' => string '2009091008262025'
'email' => string 'fred#example.com'
'userid' => string '103'
array
3 =>
array
'orderid' => string '2009091008272082'
'email' => string 'tom#example.com'
'userid' => string '392'
How can I search for duplicate orders from the same person in a given array, in PHP?
I would like to output the above like so:
(pretend its in a table)
2009091008261662 - john#example.com - 53
2009091008261048 - john#example.com - 53
2009091008262025 - fred#example.com - 103
2009091008272082 - tom#example.com - 392
... so basically just highlight the two ( or more ) duplicates.
Assumes uniqueness based on userid value
<?php
$orders = array(
array(
'orderid' => '2009091008261662',
'email' => 'john#example.com',
'userid' => '53'
),
array(
'orderid' => '2009091008261048',
'email' => 'john#example.com',
'userid' => '53'
),
array(
'orderid' => '2009091008262025',
'email' => 'fred#example.com',
'userid' => '103'
),
array(
'orderid' => '2009091008272082',
'email' => 'tom#example.com',
'userid' => '392'
),
array(
'orderid' => '2009091008265555',
'email' => 'john#example.com',
'userid' => '53'
)
);
$foundIds = array();
foreach ( $orders as $index => $order )
{
if ( isset( $foundIds[$order['userid']] ) )
{
$orders[$index]['is_dupe'] = true;
$orders[$foundIds[$order['userid']]]['is_dupe'] = true;
} else {
$orders[$index]['is_dupe'] = false;
}
$foundIds[$order['userid']] = $index;
}
?>
<style type="text/css">
tr.dupe td {
font-weight: bold;
}
</style>
<table>
<tr><th>orderid</th><th>email</th><th>
<?php foreach ( $orders as $order ) { ?>
<tr class="<?php echo $order['is_dupe'] ? 'dupe' : '' ?>">
<td><?php echo $order['orderid']; ?></td>
<td><?php echo $order['email']; ?></td>
<td><?php echo $order['userid']; ?></td>
</tr>
<?php } ?>
</table>
Your best bet would be essentially "invert" the array into an associative one mapping values to keys from the original array:
$emails = array();
$userids = array();
foreach($inputarray as $key => $item) {
if( isset($emails[$item['email']]) || isset($userids[$item['userid']]) ) {
// This item has a duplicate email or userid as something already looked at!
// $emails[$item['email']] or $userids[$item['userid']] has the key corresponding to the original location where it was seen.
// $key has the key corresponding to the duplicate we just found.
} else {
$emails[$item['email']] = $key;
$userids[$item['userid']] = $key;
}
}
You could add a hash to the inner-array which represents the the array. Just loop through and compare the hashes.
This code works...
$array1[0]['orderid'] = '2009091008261662';
$array1[0]['email'] = 'john#example.com';
$array1[0]['userid'] = '53';
$array1[1]['orderid'] = '2009091008261662';
$array1[1]['email'] = 'john#example.com';
$array1[1]['userid'] = '53';
$array1[2]['orderid'] = '2009091008261662';
$array1[2]['email'] = 'john2#example.com';
$array1[2]['userid'] = '53';
$array1[3]['orderid'] = '209091008261662';
$array1[3]['email'] = 'joh3#example.com';
$array1[3]['userid'] = '53';
$array1[4]['orderid'] = '2001008261662';
$array1[4]['email'] = 'john#example.com';
$array1[4]['userid'] = '53';
$array1[5]['orderid'] = '20013344008261662';
$array1[5]['email'] = 'johnddd#example.com';
$array1[5]['userid'] = '53';
$array1[6]['orderid'] = '200133352008261662';
$array1[6]['email'] = 'johsdfgsdn#example.com';
$array1[6]['userid'] = '53';
$unique_array = array(); // Filtered array with no dupes
$email_array = array(); // Hash list
$order_array = array(); // Hash list
foreach($array1 as $i => $row) {
if (array_key_exists($row['email'], $email_array)) {
// This is a dupe based on email
$array1[$i]['duplicate'] = 1;
$array1[$email_array[$row['email']]]['duplicate'] = 1;
}
if (array_key_exists($row['orderid'], $order_array)) {
// This is a dupe based on email
$array1[$i]['duplicate'] = 1;
$array1[$order_array[$row['orderid']]]['duplicate'] = 1;
}
$order_array[$row['orderid']] = $i;
$email_array[$row['email']] = $i;
}
foreach($array1 as $i => $row) {
if (!empty($row['duplicate'])) {
echo "<b>" . $row['orderid'] . $row['email'] . "</b>\n";
unset($row['duplicate']); // reset the array to original form
} else {
echo $row['orderid'] . $row['email'] . "\n";
}
}
You'll need two passes of the orders array. But it's really more simple than some have made it out to be:
$duplicateUserId = array();
// Mark user ID's with more than one order
foreach ( $orders as $order ) {
$duplicateUserId[$order['userid']] = isset($duplicateUserId[$order['userid']]);
}
// Output each order
foreach ( $orders as $order ) {
echo formatOrder($order, $duplicateUserId[$order['userid']]);
}
// Format the output of each order
function formatOrder($order, $isDuplicated) {
// yadda yadda yadda
}
Assuming that $orders looks like
$orders = array(
array(
'orderid' => '2009091008261662',
'email' => 'john#example.com',
'userid' => '53'
),
array(
'orderid' => '2009091008261048',
'email' => 'john#example.com',
'userid' => '53'
),
array(
'orderid' => '2009091008262025',
'email' => 'fred#example.com',
'userid' => '103'
),
array(
'orderid' => '2009091008272082',
'email' => 'tom#example.com',
'userid' => '392'
),
array(
'orderid' => '2009091008265555',
'email' => 'john#example.com',
'userid' => '53'
)
);
Also, it might be best to only match on userId since, presumably, users can change their emails and emails are unique to a single user.
Simple answer:
function hasDuplicate($arr,$email) {
$count = 0;
foreach ($arr as $row) {
if ($row['email'] == $email) {
$count++;
}
}
return ($count >1);
}

Categories