I am trying to create an array which will have two key/value pairs for each user. I would like to add their user ID as well as their name.
Currently I have this:
<?php
$userArray = array();
foreach ($users as $user) {
array_push($userArray, $user->ID, $user->name);
}
print_r($userArray);
?>
This gives me the following:
Array ([0] => 167 [1] => Bill [2] => 686 [3] => Jim [4] => 279 [5] => Tom)
However, to make it easier to read and work with, I would prefer that it shows user_id and user_name as the keys, rather than just the index. I believe this is what's called a multidimensional array and would look more like this:
Array (
0 => array(
'user_id' => 167,
'user_name' => 'Bill'
),
1 => array(
'user_id' => 686,
'user_name' => 'Jim'
),
2 => array(
'user_id' => 279,
'user_name' => 'Tom'
)
)
My question is how would I build an array like this within my foreach loop?
You just need to create the new array and add it to the $userArray, I use [] instead of array_push() though...
$userArray[] = [ 'user_id' => $user->ID, 'user_name' => $user->name];
you should be pushing a new array, like this :
<?php
$userArray = array();
foreach ($users as $user) {
array_push($userArray, ['user_id' => $user->ID, 'user_id' => $user->name]);
}
print_r($userArray);
?>
Related
I got the follwing array and I would like to retrieve the name by the id:
Array
(
[0] => Array
(
[id] => 1
[name] => john
)
[1] => Array
(
[id] => 2
[name] => mark
)
etc...
It is doable with double foreach loop and a conditional test, but is there a more elegant way?
Assuming that id is unique...
Long Version
$arr = [
['id'=1, 'name'='john'],
['id'=2, 'name'='mark'],
];
$lookup = [];
foreach($arr as $row) {
$id = $row['id'];
$name = $row['name'];
$lookup[$id] = $name;
}
// find name for id, 2
echo $lookup[2];
// ==> mark
Short Version
...see Progrock’s solution!
You can use array_column to map ids to names:
<?php
$arr = [
['id' => 1, 'name' => 'Rolf'],
['id' => 3, 'name' => 'Gary'],
['id' => 2, 'name' => 'Jimmy'],
];
$id_names = array_column($arr, 'name', 'id');
var_export($id_names);
print $id_names[3];
Output:
array (
1 => 'Rolf',
3 => 'Gary',
2 => 'Jimmy',
)Gary
I have two arrays:
$arr1 = [
[
'id' => 1,
'name' => 'John',
'email' => 'j#mail.com'
],
[
'id' => 2,
'name' => 'Jane',
'email' => 'jane#mail.com'
]
];
And the second array:
$arr2 = [
[
'id' => 1,
'email' => 'john#yahoo.com'
],
[
'id' => 2,
'email' => 'jane#yahoo.com'
],
[
'id' => 2,
'email' => 'jane.doe#hotmail.com'
],
];
I would like to add all values with the same 'id' from the second array to the first array. The result I expect would be:
$arr3 = [
[
'id' => 1,
'name' => 'John',
'email' => ['j#mail.com', 'john#yahoo.com']
],
[
'id' => 2,
'name' => 'Jane',
'email' => ['jane#mail.com', 'jane#yahoo.com', 'jane.doe#hotmail.com']
]
];
This code will do what you want. It goes through all the entries of $arr2, looking for matching id values in $arr1 and, where it finds them, adding the email address from $arr2 to the list of emails in $arr1 for that id value:
foreach ($arr2 as $arr) {
if (($k = array_search($arr['id'], array_column($arr1, 'id'))) !== false) {
if (is_array($arr1[$k]['email'])) {
$arr1[$k]['email'][] = $arr['email'];
}
else {
$arr1[$k]['email'] = array($arr1[$k]['email'], $arr['email']);
}
}
}
Output:
Array (
[0] => Array (
[id] => 1
[name] => John
[email] => Array (
[0] => j#mail.com
[1] => john#yahoo.com
)
)
[1] => Array (
[id] => 2
[name] => Jane
[email] => Array (
[0] => jane#mail.com
[1] => jane#yahoo.com
[2] => jane.doe#hotmail.com
)
)
)
I agree with #Barmar's comment under the question; it will be more direct/efficient and boast a superior computational time complexity to iterate the second array to populate a lookup array and reference it while iterating the first array versus doing full scans and searches of the first array for every row of the second array.
This implementation forms the lookup array using array destructuring syntax in a body-less foreach() loop. Then another foreach() loop iterates the first array using array destructuring syntax, modifying the rows' email element, and checking if there are any emails to add to the first array's email.
Even if no corresponding row exists in the second array, the first array's email string will be cast as a single-element array for consistency.
Code: (Demo)
foreach ($arr2 as ['id' => $id, 'email' => $lookup[$id][]]);
foreach ($arr1 as ['id' => $id, 'email' => &$email]) {
$email = array_merge((array) $email, $lookup[$id] ?? []);
}
var_export($arr1);
The name element does not need to be mentioned during array destructuring because there are no subsequent processes applied to it in the loops.
I try like this :
<?php
$list_team = array(
(object)array(
'id' => 1,
'name' => 'chelsea.jpg'
),
(object)array(
'id' => 2,
'name' => 'mu.jpg'
),
(object)array(
'id' => 3,
'name' => 'arsenal.jpg'
),
);
$team = 'chelsea.jpg';
echo '<pre>';print_r($team);echo '</pre>';
echo '<pre>';print_r($list_team);echo '</pre>';
foreach($list_team as $key => $value) {
if($value->name == $team)
$team_selected = $team;
}
echo '<pre>';print_r($team_selected);echo '</pre>';
die();
?>
If the code executed, the result like this :
chelsea.jpg
Array
(
[0] => stdClass Object ( [id] => 1
[name] => chelsea.jpg
)
[1] => stdClass Object
(
[id] => 2
[name] => mu.jpg
)
[2] => stdClass Object
(
[id] => 3
[name] => arsenal.jpg
)
)
chelsea.jpg
The code using loop
But, I do not want to use a loop
How can I do it?
Try the following:
$key = array_search($team, array_column($list_team, 'name'));
$team_selected = $list_team[$key]->name;
This will search array with name and return the and return the key of the main array and you can use that to access the contents of the nested array and assign the value to. $team_selected
Using array_search(), and array_column()
<?php
$list_team = array(
(object)array(
'id' => 1,
'name' => 'chelsea.jpg'
),
(object)array(
'id' => 2,
'name' => 'mu.jpg'
),
(object)array(
'id' => 3,
'name' => 'arsenal.jpg'
),
);
$team = 'chelsea.jpg';
// array column, returns all value of sub array, with key name
// array_search will return key
$key = array_search($team, array_column($list_team, 'name'));
if($key!==false){
// your object will be
print_r($list_team[$key]);
// access remaining..
echo $list_team[$key]->name.' '. $list_team[$key]->id.PHP_EOL;
}
?>
If you want to access specific attributes in multidimensional arrays, you can do the following thing.
For example, return the ID of the first array:
echo $list_team[0]["id"];
Simply change the [0] to [1] or whatever to mention the array you wanna call, and then simply use the attribute. But if you wanna print the whole array, I really recommend you to stay on loops. With loops you're sure you get all elements. Lets say you hardcode it like I said and then a month later you add 10 new arrays, so you'll have to edit your whole code.
regarding in query from the model, i got already the values and store it from a variable, now i want it to be stored from a data array for further use, how can i do this, i am in controller from codeigniter.
Here is my controller full code:
public function move_data($queue_id) {
$data = array();
$user = array('user_id' => $this->session->userdata['logged_in']['user_id']);
$getqueuedata = $this->Clinic_model->queue_data($queue_id,$user);
//echo json_encode($getqueuedata);
$data = array (
'queue_id' => $getqueuedata['queue_id'],
'user_id' => $getqueuedata['user_id'],
'clinic_id' => $getqueuedata['clinic_id'],
'order_num' => $getqueuedata['order_num'],
'patient_id' => $getqueuedata['patient_id'],
);
}
when i //echo json_encode($getqueuedata); uncomment this line, and comment the array storing, i will have this:
[{"user_id":"102","clinic_id":"2","order_num":"1","patient_id":"7","status":"2","time_sched":null,"queue_id":"1"}]
in my full code, i got error, i dont know how to store the values of my query from array.
function 'queue_data` return result like this :
//$getqueuedata = json_decode($json,true);
Array ( [0] => Array ( [user_id] => 102 [clinic_id] => 2 [order_num] => 1 [patient_id] => 7 [status] => 2 [time_sched] => [queue_id] => 1 ) )
So you can store data as this way:
$data = array (
'queue_id' => $getqueuedata[0]['queue_id'],
'user_id' => $getqueuedata[0]['user_id'],
'clinic_id' => $getqueuedata[0]['clinic_id'],
'order_num' => $getqueuedata[0]['order_num'],
'patient_id' => $getqueuedata[0]['patient_id'],
);
print_r($getqueuedata);
If your function return array object:
$data = array (
'queue_id' => $getqueuedata[0]->queue_id,
'user_id' => $getqueuedata[0]->user_id,
'clinic_id' => $getqueuedata[0]->clinic_id,
'order_num' => $getqueuedata[0]->order_num,
'patient_id' => $getqueuedata[0]->patient_id,
);
I currently have an array, created from a database, an example of which looks like the following:
Array(
[0] => Array (
objectid => 2,
name => title,
value => apple
),
[1] => Array (
objectid => 2,
name => colour,
value => red
),
[2] => Array (
objectid => 3,
name => title,
value => pear
),
[3] => Array (
objectid => 3,
name => colour,
value => green
)
)
What I would like to do is group all the items in the array by their objectid, and convert the 'name' values into keys and 'value' values into values of an associative array....like below:
Array (
[0] => Array (
objectid => 2,
title => apple,
colour => red
),
[1] => Array (
objectid => 3,
title => pear,
colour => green
)
)
I've tried a few things but haven't really got anywhere.. Any ideas?
Thanks in advance
This should work with your current setup and should be able to handle as many key-value pairs as available:
<?php
$results = array(
array('objectid' => 2, 'name' => 'title', 'value' => 'apple'),
array('objectid' => 2, 'name' => 'color', 'value' => 'red'),
array('objectid' => 3, 'name' => 'title', 'value' => 'pear'),
array('objectid' => 3, 'name' => 'color', 'value' => 'green'));
$final = array();
foreach ($results as $result) {
$final[$result['objectid']]['objectid'] = $result['objectid'];
$final[$result['objectid']][$result['name']] = $result['value'];
}
print_r($final);
It would be easier to have the array keys correspond with your object id, that way you can iterate through your existing array, and add the key-value pairs for each object, like so:
$newArray = array();
foreach ($results as $result) {
if (!array_key_exists($result['objectid'], $newArray)) {
$newArray[$result['objectid'] = array();
}
foreach ($result as $key => $value) {
$newArray[$result['objectid'][$key] = $value;
}
}
Peter's method is perfectly valid, I just thought I would show a shorter version of the same thing (couldn't do in a comment)
foreach( $array as $obj ) {
if( !isset( $objects[$obj['objectid']] ) )
$objects[$obj['objectid']]['objectid'] = $obj['objectid'];
$objects[$obj['objectid']][$obj['name']] = $obj['value'];
}