$groups = [];
foreach($data as $user)
{
$userGroupId = $user['GroupId'];
$exists = false;
foreach($groups as $group)
{
$groupId = $group['GroupId'];
if ($groupId == $userGroupId)
{
$users = $group['users'];
$currentUser = array(
'UserId'=>$user['UserId'],
'UserName'=>$user['UserName'],
'Surname'=>$user['Surname']
);
array_push($users, $currentUser);
$exists = true;
break;
}
}
if (!$exists)
{
$addGroup = array(
'GroupId'=>$user['GroupId'],
'GroupName'=>$user['GroupName'],
'users'=>[array(
'UserId'=>$user['UserId'],
'UserName'=>$user['UserName'],
'Surname'=>$user['Surname']
)]
);
array_push($groups, $addGroup);
}
}
So i have an empty array called groups.
The original data is an array of different users including what group they are in which i am trying to sort into an array of groups with an array of users inside.
Everything works fine except when I am trying to push the current user to the users array.
When debugging I have printed the array after pushing and it has pushed fine but when it comes to the next user, the previous users have gone. So its pushed but then taken it out after.
If I get you right, you should use references:
foreach($groups as $group) -> foreach($groups as &$group)
$users = $group['users']; -> $users = &$group['users'];
Related
I am still learning php - but I want to modify a working php page and check a MySQL table for isactive then only return users if it is set to 1.
The page originally said:
foreach ($users as $U) {
if (!$U['name'])
list($name) = explode('#', $U['default_email__address']);
else
$name = new UsersName($U['name']);
I tried this, but it isn't working:
foreach ($users as $U) {
if ($U->filter(array('isactive' => 1)));
if (!$U['name'])
list($name) = explode('#', $U['default_email__address']);
else
$name = new UsersName($U['name']);
and the rest of the page works fine. I am not sure if I should add my if statement at the top of the page, before the "foreach" or as part of the "foreach". I am not even positive I have correct way to pull the field value.
$U appears to be an associative array. They aren't objects with methods. If you want to get isactive, just use $U['isactive']
foreach ($users as $U) {
if ($U['isactive') {
if (!$U['name']) {
list($name) = explode('#', $U['default_email__address']);
} else {
$name = new UsersName($U['name']);
}
}
}
This is my addToCart method in which I am adding the courses to user_cart column in users table.
public function addToCart($id){
$course = Course::findOrfail($id);
$user =Auth::user();
$cart_array = array();
$cart = $user->user_cart;
if ($cart == '') {
array_push($cart_array, array('id' => $course->id));
// print_r($cart_array);
} else {
$founder = false;
$cart_array = json_decode($cart, true);
for ($i = 0; $i < count($cart_array); $i++) {
$cart_for_eacch_course = $cart_array[$i];
if ($cart_for_eacch_course['id'] == $course->id) {
$founder = true;
}
}
if (!$founder) {
array_push($cart_array, array('id' => $course->id));
}
}
$data['id'] = json_encode($cart_array);
$update = User::where('id',$user->id)->update(['user_cart'=> $cart_array]);
return redirect()->back();
}
And this is my showcart method in which I am taking the courses from users table user_cart column array.
public function showcart(){
$user = Auth::user();
$array = $user->user_cart;
print_r($array);
return view('frontend.my_cart', compact('academic','nonacademic','instructor','coc','my_cart'));
}
And when I am displaying it I am getting the output as follows:
[{"id":84},{"id":86}]
Now can you tell me that how to loop them so I can get the courses? I tried by using a foreach loop for $array but it shows me the error of invalid argument supplied for foreach()
Looks like you are building the array into a JSON or string field within your database on the User object. The resulting array appears to be stored as a JSON string, so decode and then loop:
$array = json_decode( $user->user_cart, true );
foreach($array as $key => $val){
dump $key;
dump $val;
}
I wrote an api call in my Symfony project that returns all fields from my entity with the query defined below..
Now, I need to define just three fields like 'id', 'name', 'value' and to pull values from that fields that are currently stored in a database.
public function getChartData() {
$myResults = $this->getMyRepository()
->createQueryBuilder('s')
->groupBy('s.totalCollected')
->orderBy('s.id', 'ASC')
->getQuery()
->getArrayResult();
$result = array("data" => array());
foreach ($myResults as $myResult => $label) {
$result['data'][$schoolResult] = $label["id"];
$result['data'][$schoolResult] = $label["name"];
$result['data'][$schoolResult] = $label["totalCollected"];
}
}
The problem is it return just totalCollected field.
One of errors are Call to a member function getId() on array and so on, and I can't figure out a way to pull data from db...
I cannot see in your code where $schoolResult come from but lets guess it string key of some sort.
Notice you trying to set 3 value on the same key so only the last one remains.
Look at:
$a = array();
$a["key"] = 4;
$a["key"] = 6;
It is simple to see that $a["key"] will contains 6 and not 4 or both.
When you do:
foreach ($myResults as $myResult => $label) {
$result['data'][$schoolResult] = $label["id"];
$result['data'][$schoolResult] = $label["name"];
$result['data'][$schoolResult] = $label["totalCollected"];
}
You override the data in $result['data'][$schoolResult] therefor only try totalCollected is there as the last one to set.
In order to fix that you can use:
foreach ($myResults as $myResult => $label) {
$result['data'][$schoolResult]["id] = $label["id"];
$result['data'][$schoolResult]["name"] = $label["name"];
$result['data'][$schoolResult]["totalCollected"] = $label["totalCollected"];
}
Hope that helps!
$user = hobaa;
$usernames = array();
$usernames['name'] = $user;
print_r($usernames['name']);
Will issue something like
Array ( [name] => hobaa )
and print_r($usernames); will issue this out hobaa
How can I make it save multiple values?
Tried
$users = array("hobaa","test");
foreach($users as $user) {
$usernames = array();
$usernames['name'][] = $user;
}
print_r($usernames['name']);
But it just takes the last value.
Please help. Thanks!
From this code:
foreach($users as $user) {
$usernames = array();
$usernames['name'][] = $user;
}
remove this line from loop:
$usernames = array();
and put it above the loop like:
$usernames = array();
foreach($users as $user) {
$usernames['name'][] = $user;
}
and try again. As you are re-initializing the array on every iteration.
Something like:
$users = array("hobaa","test");
// a new usernames array to use
$usernames = array();
//
foreach($users as $user) {
array_push($usernames, $user);
}
print_r($usernames);
Will give:
Array ( [0] => hobaa [1] => test )
Define $usernamse variable outside of the loop. Use the following code :
$users = array("hobaa","test");
$usernames = array();
foreach($users as $user) {
$usernames['name'][] = $user;
}
print_r($usernames['name']);
the following algorithm add users to a company array. I want to add a total of user for any given company. Howd I go about doing that
public function all_company_information($id = null){
$arrCompany = array();
$arrCompany['company']= array();
$arrData = array();
$this->autoRender = false;
$this->loadModel("User");
$users = $this->User->find('all');
foreach($users as $k => $user){
if(!in_array($user['User']['company_id'], $arrCompany['company'])){
$arrCompany['company'][$user['User']['company_id']][] = $user;
}else{
$arrCompany['company'][$user['User']['company_id']][] = $user;
}
}
}
Do a find on the Company model, then you can get a count of users easily.
$results = $this->Company->find('all');
foreach($results as $k => $company) {
$results[$k]['Company']['user_count'] = count($company['User']);
}
Something along those lines. The returned results will be an array of Company records and each Company record will have a list of associated user records in the User key.