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]
];
}
Related
I want to get most and least occuring values from php sequential/indexes, assoc and multidimensional arrays
Consider the following dataSet
$dataSet = [
'users' =>
[
'id' => 1,
'name' => "Alex",
'username' => 'alex',
],
[
'id' => 2,
'name' => "Alex",
'username' => 'alex'
],
[
'id' => 2,
'name' => "Peter Khot",
'username' => 'peter',
]
];
Here above are samples dataSet
Here is what that i tried
function most_occurring(array $array, $key)
{
$dataSet = [];
$i = 0;
$keys = [];
foreach ($array as $k) {
if (in_array($k[$key], $keys)) {
$keys[$i] = $k[$key];
$dataSet[$i] = $k;
}
$i++;
}
return $dataSet;
}
I tried above code for most occurring values but not working at all, help me in most and least occuring values from arrays.
Thanks
Thanks to KIKO Software, you can still use array_count_values() for this cases. You will also need to use array_columns() and array_search() in this situation. You can refer to this link to see how array_search() helps in finding the maximum/minimum value and its corresponding key inside an array. To find the most or least occurrence, simply echo the last 6 variables that I have declared in the last 6 lines.
EDIT* reference:
unset
array_push
*And also, your first data in the assoc array is indexed 'user', but the second data in the assoc array is not indexed and hence it is indexed as 0.
$dataSet = [
'users' =>
[
'id' => 1,
'name' => "Alex",
'username' => 'alex',
],
[
'id' => 2,
'name' => "Alex",
'username' => 'alex'
],
[
'id' => 2,
'name' => "Peter Khot",
'username' => 'peter',
]
];
$id = array_column($dataSet,'id');
$name = array_column($dataSet, 'name');
$username = array_column($dataSet, 'username');
$occur_id = array_count_values($id);
$occur_name = array_count_values($name);
$occur_username = array_count_values($username);
$most_occur_id = array_search(max($occur_id),$occur_id);
$most_occur_name = array_search(max($occur_name),$occur_name);
$most_occur_username = array_search(max($occur_username),$occur_username);
$least_occur_id = array_search(min($occur_id),$occur_id);
$least_occur_name = array_search(min($occur_name),$occur_name);
$least_occur_username = array_search(min($occur_username),$occur_username);
EDIT*: (In case of multiple highest occurence OR all same occurence, just add below code right below the above code.)
$flag = true;
$most_occur_name_list = [];
$count = 0;
while($flag)
{
$most_occur_name_ct = max($occur_name);
if($most_occur_name_ct == $count || $count == 0)
{
array_push($most_occur_name_list,array_search($most_occur_name_ct,$occur_name));
unset($occur_name[array_search($most_occur_name_ct,$occur_name)]);
$count = $most_occur_name_ct;
if(count($occur_name) == 0)
{
$flag = false;
break;
}
}
else
{
$most_occur_name_ct = $count;
$flag = false;
break;
}
}
//must reinitialize the array
$occur_name = array_count_values($name);
$flag = true;
$least_occur_name_list = [];
$count = 0;
while($flag)
{
$least_occur_name_ct = min($occur_name);
if($least_occur_name_ct == $count || $count == 0)
{
array_push($least_occur_name_list,array_search($least_occur_name_ct,$occur_name));
unset($occur_name[array_search($least_occur_name_ct,$occur_name)]);
$count = $least_occur_name_ct;
if(count($occur_name) == 0)
{
$flag = false;
break;
}
}
else
{
$least_occur_name_ct = $count;
$flag = false;
break;
}
}
if($most_occur_name_ct == $least_occur_name_ct)
{
$most_occur_name_list = [];
$least_occur_name_list = [];
}
echo "<pre>";
print_r($most_occur_name_list);
If you wanted to get a list of the min and max number of occurrences for just 1 element of the multidimensional array, then this code may offer a shorter method - comments in code...
$dataSet = [
'users' =>
[
'id' => 1,
'name' => "Alex",
'username' => 'alex',
],
[
'id' => 2,
'name' => "Alex",
'username' => 'alex'
],
[
'id' => 2,
'name' => "Peter Khot",
'username' => 'peter',
],
[
'id' => 2,
'name' => "Peter Khot",
'username' => 'peter',
],
[
'id' => 2,
'name' => "Paul Khot",
'username' => 'Paul',
]
];
// Create an array which has the username column, but retaining the keys from
// the original array
$set = array_combine(array_keys($dataSet),
array_column($dataSet, "username" ));
// Summarise the values
$count = array_count_values($set);
// Get a list of the keys which match the max and min values
$minRecords = array_keys($count,min($count));
$maxRecords = array_keys($count,max($count));
// Fetch the details for the maximum value (first one returned)
$maxElements = [];
foreach ( $maxRecords as $max ) {
$maxElements[] = $dataSet[array_search($max, $set )];
}
// Same for min values
$minElements = [];
foreach ( $minRecords as $min ) {
$minElements[] = $dataSet[array_search($min, $set )];
}
print_r($maxElements);
print_r($minElements);
With the test data I've added, you get the output...
Array
(
[0] => Array
(
[id] => 1
[name] => Alex
[username] => alex
)
[1] => Array
(
[id] => 2
[name] => Peter Khot
[username] => peter
)
)
Array
(
[0] => Array
(
[id] => 2
[name] => Paul Khot
[username] => Paul
)
)
I have an array as
$apps = array(
array(
'id' => '2',
'name' => 'Popcorn'
),
array(
'id' => '1',
'name' => 'EveryCord'
),
array(
'id' => '2',
'name' => 'AirShou'
),
Here I want to print names where id="2". So I tried it with following code.
foreach ( $apps as $var ) if ($var['id'] == "2") {
echo $var['name']
}
The problem is that it only print first result of the array as
"Popcorn".
But I want to extract all result which are
"Popcorn and Airshou"
How can I fix this. Can someone help me !
Try this;
$apps = [
['name' => 'Fish', 'id' => 2],
['name' => 'Chips', 'id' => 1],
['name' => 'Sticks', 'id' => 2],
];
$using = [];
foreach ( $apps as $var ) {
if ($var['id'] == "2") {
$using[] = $var['name'];
}
}
echo implode(" and ", $using);
RESULT:
You can create a sample array.
And append the name to it, if it is id=2
Code:
$apps = [
['id' => '2', 'name' => 'Popcorn'],
['id' => '1', 'name' => 'EveryCord'],
['id' => '2', 'name' => 'AirShou']
];
$names = [];
if (! empty($apps)) {
foreach ($apps as $elem) {
if ($elem['id'] == 2) {
$names[] = $elem['name'];
}
}
}
$finalName = ! empty($names) ? implode(' and ', $names) : '';
echo '<pre>';print_r($finalName);echo '</pre>';
// Output: Popcorn and AirShou
You can filter the array on the item id and then retrieve the column name:
array_column(array_filter($apps, function($v){return '2' === $v['id'];}), 'name')
result:
array(2) {
[0] =>
string(7) "Popcorn"
[1] =>
string(7) "AirShou"
}
Change your loop by this code, and you will got both names,
foreach ( $apps as $var ){
if ($var['id'] == "2") {
echo $var['name'];
}
}
Just grab names in array then implode it like this:
$temp = array();
foreach ( $apps as $var ) if ($var['id'] == "2") {
$temp[] = $var['name']
}
echo implode(' and ', $temp);
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();
}
Lets suppose i have the following array submitted by a html form:
array(
'firstname' => array('Sara','Jim'),
'lastname' => array('Gibson','Jobs')
);
What i wanna achieve is the following array:
array(
array(
'firstname' => 'sara',
'lastname' => 'Gibson'
),
array(
'firstname' => 'Jim',
'lastname' => 'Jim'
)
);
I need a function to automatically sort the array not manually by entering data but automatically processing array data.
$new_arr = array();
$length = count($arr['firstname']);
for($i = 0; $i < $length; $i++)
{
$new_arr[] = array('firstname' => $arr['firstname'][$i], 'lastname' => $arr['lastname'][$i]);
}
I don't see anything wrong with #Tim Cooper's solution, but if you don't want to mention the keys manually, you can also use:
$new_arr = array();
foreach ($arr as $key => $value)
{
foreach ($value as $numkey => $value2)
{
$new_arr[$numkey][$key] = $value2;
}
}
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);
}