How can i remove one Object and rename all object sequence wise - php

array
i want to remove one object form module ex module_1 as i give in html data-modulename and rename all module name sequence wise. like moduel_2 module_3... and rename module_1 module_2...
array(1) {
[0]=>
object(App\Models\Course)#1268 (30) {
["connection":protected]=>
string(5) "mysql"
["table":protected]=>
string(7) "courses"
["primaryKey":protected]=>
string(2) "id"
["keyType":protected]=>
string(3) "int"
["incrementing"]=>
bool(true)
["with":protected]=>
array(0) {
}
["withCount":protected]=>
array(0) {
}
["preventsLazyLoading"]=>
bool(false)
["perPage":protected]=>
int(15)
["exists"]=>
bool(true)
["wasRecentlyCreated"]=>
bool(false)
["escapeWhenCastingToString":protected]=>
bool(false)
["attributes":protected]=>
array(9) {
["id"]=>
int(4)
["coursename"]=>
string(11) "science new"
["awardingbody"]=>
string(23) "Qualifi, United Kingdom"
["ofqualregistrationnumber"]=>
string(8) "34443234"
["totalcredits"]=>
string(5) "34242"
["numbersmodules"]=>
string(1) "2"
["modules"]=>
string(672) "{"module_1":{"modulename":"sdfsdf","moduletypes":"mandatory","moduleid":"32432","moduleaim":"sdfsdfsf","learningobjectives":"sdfsfsfd","assessmentcriteria":"sdfsfdsdf","scenario":"sdfsdf","tasknumber":2,"taskarea":["sdfsdfsf","adsdasdsd"],"librarylinks":["sdsfsf"],"studylinks":["sdfsdfsdf"],"videoslinks":["sdfsdsf"]},"module_2":{"modulename":"sdfsdfsdf","moduletypes":"optional","moduleid":"34234","moduleaim":"sdfsdfsdf","learningobjectives":"sdfsdfs","assessmentcriteria":"sdfsdsdfs","scenario":"sddssssd","tasknumber":2,"taskarea":["sdsdfsdf","sdsdfsdf"],"librarylinks":["sdsdfsdf","sdfsdffs"],"studylinks":["sdfsdf","sdfsdf"],"videoslinks":["sdfsdfs","sdfsfsdfsf"]}}"
["created_at"]=>
string(10) "1673082184"
["updated_at"]=>
string(10) "1673082214"
}
html
<button class="btn rounded-pill btn-primary remove_module remove_module_button" type="button" data-id="4" data-modulename="module_1">Remove Module <i class="bx bx-x-circle ml-1"></i></button>
js
`$(document).on('click', '.remove_module', function() {
$confirm = confirm("Are you Sure you want to delete this module");
if ($confirm == true) {
$this = $(this);
$id = $this.data('id');
$modulename = $this.data('modulename');
$.ajax({
method: "GET",
url: "deletemodule",
data: {
id: $id,
modulename: $modulename
},
success: function(data) {
if (data == 1) {
alert("Service Start Successfully!");
window.location.reload();
}
}
});
}
});`
php
`public function deleteModule(Request $request){
$id = $request->id;
$modulename = $request->modulename;
$data = Course::where('id', $id)->get();
$module = $data[0]->modules;
$json = json_decode($module);
$result = [];
foreach($json as $key => $value) {
if($value->$modulename != $modulename) {
$result[] = $value;
}
}
$update = [
'module' => json_encode($result)
];
Course::where('id', $id)->update($update);
echo 1;
}`

Related

Structure array into multi dimensional array

So I have the following variable $authenticated_users which returns:
array(2) {
[0]=>
array(5) {
["username"]=> string(16) "saint"
["user_id"]=> int(17841404774727369)
["access_token"]=> string(142) "IGQ3"
["access_token_expiration"]=> int(1650688769)
["last_updated"]=> int(1645537675)
}
[1]=>
array(5) {
["username"]=> string(9) "sem"
["user_id"]=> int(17841400835712753)
["access_token"]=> string(140) "IGQ"
["access_token_expiration"]=> int(1650683675)
["last_updated"]=> int(1645537891)
}
}
So I have the following method:
public static function get_config_and_users(): array
{
$config = [];
$config['client_id'] = '2882';
$config['client_secret'] = '521f4e';
if (!$authenticated_users = get_option('instagram')) {
return [];
}
foreach ($authenticated_users as $user) {
$config['authenticated_users'] = [
$config['username'] = $user['username']
];
}
echo '<pre>';
var_dump($config);
echo '</pre>';
die();
return $config;
}
When I echo $config I get the following results:
array(4) {
["client_id"]=> string(15) "28822"
["client_secret"]=> string(32) "521f4e8"
["username"]=> string(9) "sem"
["authenticated_users"]=> array(1) {
[0]=> string(9) "sem"
}
}
Here is what I'm attempting to do:
array(4) {
["client_id"]=> string(15) "2882"
["client_secret"]=> string(32) "521f4e5"
["authenticated_users"] => {
[0]=> array(1) {
['username']=> string(16) "saint"
....
}
[1]=>
array(1) {
['username']=> string(9) "sem"
....
}
}
}
Does anyone know what I can do to improve my code?
you need to change your logic
public static function get_config_and_users(): array
{
$config = [];
$config['client_id'] = '2882';
$config['client_secret'] = '521f4e';
if (!$authenticated_users = get_option('instagram')) {
return [];
}
foreach ($authenticated_users as $user) {
$config['authenticated_users'][] = [
'username' => $user['username']
];
}
return $config;
}

Get path to parent node of (parent/child) array

Given the following array:
array(..) {
[1111]=>
&array(3) {
["category_id"]=>
int(1111)
["parent_id"]=>
int(0)
["children"]=>
array(2) {
[2222]=>
&array(3) {
["category_id"]=>
int(2222)
["parent_id"]=>
int(1111)
["children"]=>
array(2) {
[5555]=>
&array(1) {
["category_id"]=>
int(5555)
["parent_id"]=>
int(2222)
}
}
[3333]=>
&array(2) {
["category_id"]=>
int(3333)
["parent_id"]=>
int(1111)
}
}
Assuming that the array depth is unknown, How can I determine the path to the parent node?
For example, for category_id = 5555 I should get the following result: 0, 1111,2222. For category_id = 3333 it would be 0,1111
One approach:
function findParent($node, $array, &$parents) {
if (array_key_exists($node, $array)) {
$parents[] = $array[$node]['parent_id'];
}
else {
foreach ($array as $item) {
if (array_key_exists('children', $item)) {
$parents[] = $item['parent_id'];
findParent($node, $item['children'], $parents);
}
}
}
}
findParent(5555, $A, $parents);

Invalid argument for FOR EACH loop

I'm getting an error on a for each loop, saying that it get's invalid argument.
$bidder = new MuxBidder( $mailer->bidder_id );
$today = $bidder->getTodayBoughtLeads();
$legum = $bidder->getLegum();
$zipInterval = $bidder->getMeta('zip-intervals');
var_dump($bidder->getMeta('zip-intervals'));
$region = $lead->getRegion();
$zip = $lead->getZip();
// If "revisor"
if ( !$legum ) {
if( $lead->getPrice( $bidder->getId() ) >= $bidder->getMeta( 'min_clips' ) ) {
foreach ($zipInterval as $interval) {
if ($interval['from'] <= $zip && $zip <= $interval['to']) {
// "revisor" just get the lead straight away
$this->push_lead( $mailer->lead_id, $mailer->bidder_id );
return true;
}
}
}
// If Legum user ("advokat")
}
The error appears with $zipInterval. When I var_dump that variable I have:
array(1) {
[0]=> array(2) {
["from"]=> string(4) "0000" ["to"]=> string(4) "9999"
}
}
array(1) {
[0]=> array(2) {
["from"]=> string(4) "1000" ["to"]=> string(4) "9999"
}
}
array(1) {
[0]=> array(2) {
["from"]=> string(4) "1000" ["to"]=> string(4) "9999"
}
}
array(2) {
[0]=> array(2) {
["from"]=> string(4) "0000" ["to"]=> string(4) "9999"
}
[1]=> array(2) {
["from"]=> string(0) "" ["to"]=> string(0) ""
}
}
string(0) ""
Can anybody see what's wrong with the argument ?
Looks like you call this function more than once? On the last loop you get an empty string returned instead of an array.
try checking if the value is an array before iterating.
<?php
if(is_array($zipInterval)){
foreach($zipInterval as $interval){
//...
}
}

in_array not working codeigniter

I cannot get my in_array to work on my library both functions are on same library. I will not let me do
$this->user_auth->hasPermission('modify', 'folder/controller-name');
By using the function above I can check if has permission to modify.
On my library function hasPermission the $key & $value does not work.
On my login function I unserialize the permissions
I cannot figure out why that the hasPermission always returns false.
Login
public function login($username, $password) {
$user_query = $this->CI->db->query("SELECT * FROM " . $this->CI->db->dbprefix . "user
WHERE username = " . $this->CI->db->escape($username) . "
AND (password = SHA1(CONCAT(salt, SHA1(CONCAT(salt, SHA1(" . $this->CI->db->escape($password) . ")))))
OR password = " . $this->CI->db->escape(md5($password)) . ")
AND status = '1'
");
if ($user_query->num_rows() > 0) {
$this->user_id = $user_query->row('user_id');
$this->username = $user_query->row('username');
$this->user_group_id = $user_query->row('user_group_id');
$data_session = array(
'logged' => true,
'user_id' => $this->user_id
);
$this->CI->session->set_userdata($data_session);
$user_group_query = $this->CI->db->query("SELECT permission FROM " . $this->CI->db->dbprefix . "user_group
WHERE user_group_id = '" . (int)$user_query->row('user_group_id') . "'");
$permissions = unserialize($user_group_query->row('permission')); // Vardumps fine.
if (is_array($permissions)) {
foreach ($permissions as $key => $value) {
$this->permission[$key] = $value;
}
}
return true;
} else {
return false;
}
}
Has Permission
public function hasPermission($key, $value) {
if (isset($this->permission[$key])) {
return in_array($value, $this->permission[$key]);
} else {
return false;
}
}
Var Dump
array(2) {
["access"]=> array(18) {
[0]=> string(18) "catalog/Categories"
[1]=> string(27) "code_examples/Code_examples"
[2]=> string(23) "dashboard_modules/Chart"
[3]=> string(34) "dashboard_modules/Latest_customers"
[4]=> string(30) "dashboard_modules/Latest_users"
[5]=> string(14) "design/Banners"
[6]=> string(14) "design/Layouts"
[7]=> string(16) "extension/Module"
[8]=> string(15) "module/Category"
[9]=> string(16) "module/Slideshow"
[10]=> string(43) "module_code_examples/Codeigniter_controller"
[11]=> string(38) "module_code_examples/Codeigniter_email"
[12]=> string(39) "module_code_examples/Codeigniter_routes"
[13]=> string(16) "settings/Setting"
[14]=> string(14) "settings/Store"
[15]=> string(8) "tool/Log"
[16]=> string(10) "user/Users"
[17]=> string(17) "user/Users_groups"
}
["modify"]=> array(18) {
[0]=> string(18) "catalog/Categories"
[1]=> string(27) "code_examples/Code_examples"
[2]=> string(23) "dashboard_modules/Chart"
[3]=> string(34) "dashboard_modules/Latest_customers"
[4]=> string(30) "dashboard_modules/Latest_users"
[5]=> string(14) "design/Banners"
[6]=> string(14) "design/Layouts"
[7]=> string(16) "extension/Module"
[8]=> string(15) "module/Category"
[9]=> string(16) "module/Slideshow"
[10]=> string(43) "module_code_examples/Codeigniter_controller"
[11]=> string(38) "module_code_examples/Codeigniter_email"
[12]=> string(39) "module_code_examples/Codeigniter_routes"
[13]=> string(16) "settings/Setting"
[14]=> string(14) "settings/Store"
[15]=> string(8) "tool/Log"
[16]=> string(10) "user/Users"
[17]=> string(17) "user/Users_groups"
}
}
Update this is how I use the hasPermission
public function index() {
if (($this->input->server('REQUEST_METHOD') == 'POST') && $this->validateForm()) {
redirect();
}
// load view area & content
}
public function validateForm() {
if (!$this->user_auth->hasPermission('modify', 'folder/controller-name')) {
// Displays error
}
// Other checks.
}
Thanks in advance
I've done some test on a simple php file :
<?php
$mydata = array(
"test" => array("one", "two", "three")
);
var_dump(hasPermission("test", "two"));
function hasPermission($key, $value)
{
if (isset($mydata[$key]))
{
echo "here";
return in_array($value, $mydata[$key]);
}
else
{
return false;
}
}
?>
Echo : boolean false
Conclusion : $mydata[$key] does not exists.
<?php
$mydata = array(
"test" => array("one", "two", "three")
);
var_dump(hasPermission("test", "two", $mydata));
function hasPermission($key, $value, $thearray) //Pass the array through parameter
{
if (isset($thearray[$key]))
{
echo "here";
return in_array($value, $thearray[$key]);
}
else
{
return false;
}
}
?>
Echo : "here" | boolean true
Conclusion : in_array() works correctly. Your script doesn't work because hasPermission can't access to your permission array.
You can write below code to validate the permission.
function hasPermission($key, $value)
{
foreach($this->permission[$key] as $k=>$v)
{
if($v == $value) return true;
}
return false
}

How can I change the keys from an array?

I created an array in Zend Framework where I need to change some keys.
The keys are now incremented by a integer I need to increment them somehow different.
I have the following code:
public function turnoverAction()
{
$arrayTurnover = array();
$selectDebiteur = $this->tableDebiteuren->select("debiteur_id","debiteur_nummer","bedrijf_id")
->setIntegrityCheck(false)
->where('debiteur_id = 3');
$debiteur = $this->tableDebiteuren->fetchRow($selectDebiteur);
$selectverkoopHoofdpost = $this->tableVerkoopHoofdpost->select("*")
->setIntegrityCheck(false);
$verkoopHoofdposten = $this->tableVerkoopHoofdpost->fetchAll($selectverkoopHoofdpost);
$currentYear = (int)date('Y');
$amountOfYearsToShow = $currentYear - 5 + 1;
for($amountOfYearsToShow; $amountOfYearsToShow <= $currentYear; $amountOfYearsToShow++)
{
$amountOfYearsToShowBegin = $amountOfYearsToShow.'-01-01';
$amountOfYearsToShowEnd = $amountOfYearsToShow.'-12-31';
$arrayYear = array();
$totaal = 0;
foreach($verkoopHoofdposten as $verkoopHoofdpost)
{
$selectverkoopSubpost = $this->tableVerkoopSubpost->select("*")
->setIntegrityCheck(false)
->joinLeft('verkoopPost','verkoopPost.verkoopSubpost_id = verkoopSubpost.verkoopSubpost_id')
->joinLeft('verkoop_verkoopPost','verkoop_verkoopPost.verkoopPost_id = verkoopPost.verkoopPost_id')
->joinLeft('verkopen','verkopen.verkoop_id = verkoop_verkoopPost.verkoop_id')
->where('verkopen.debiteur_nummer = ' . $debiteur['debiteur_nummer'])
->where('verkopen.verkoop_factuurdatum > ? ', $amountOfYearsToShowBegin)
->where('verkopen.verkoop_factuurdatum < ? ', $amountOfYearsToShowEnd)
->where('verkoopHoofdpost_id = ' . $verkoopHoofdpost['verkoopHoofdpost_id']);
$verkoopSubposten = $this->tableVerkoopSubpost->fetchAll($selectverkoopSubpost);
$totaal_hoofdpost = 0;
foreach($verkoopSubposten as $verkoopSubpost)
{
$totaal_hoofdpost += $verkoopSubpost['verkoopPost_verkoopsom'];
}
$totaal += $totaal_hoofdpost;
$turnoverValues['post']['totaal_hoofdpost'] = number_format($totaal_hoofdpost, 2, ',', '.');
$turnoverValues['post']['hoofdpost_omschrijving'] = $verkoopHoofdpost['verkoopHoofdpost_omschrijving'];
array_push($arrayYear, $turnoverValues);
}
$turnoverValue['totaal'] = number_format($totaal, 2, ',', '.');
array_push($arrayYear, $turnoverValue);
array_push($arrayTurnover, $arrayYear);
unset($arrayYear);
}
var_dump($arrayTurnover);
}
This returns the following output:
array(2) {
[0]=>
array(2) {
[0]=>
array(1) {
["post"]=>
array(2) {
["totaal_hoofdpost"]=>
string(6) "value"
["hoofdpost_omschrijving"]=>
string(4) "value"
}
}
[1]=>
array(1) {
["post"]=>
array(2) {
["totaal_hoofdpost"]=>
string(5) "value"
["hoofdpost_omschrijving"]=>
string(8) "value"
}
}
}
[1]=>
array(2) {
[0]=>
array(1) {
["post"]=>
array(2) {
["totaal_hoofdpost"]=>
string(6) "value"
["hoofdpost_omschrijving"]=>
string(4) "value"
}
}
[1]=>
array(1) {
["post"]=>
array(2) {
["totaal_hoofdpost"]=>
string(5) "value"
["hoofdpost_omschrijving"]=>
string(8) "value"
}
}
}
}
I however need the following output:
array(2) {
[2009]=>
array(2) {
["post"]=>
array(1) {
["totaal_hoofdpost"]=>
string(6) "value"
["hoofdpost_omschrijving"]=>
string(4) "value"
}
["post"]=>
array(1) {
["totaal_hoofdpost"]=>
string(5) "value"
["hoofdpost_omschrijving"]=>
string(8) "value"
}
}
[2010]=>
array(2) {
["post"]=>
array(1) {
["totaal_hoofdpost"]=>
string(6) "value"
["hoofdpost_omschrijving"]=>
string(4) "value"
}
["post"]=>
array(1) {
["totaal_hoofdpost"]=>
string(5) "value"
["hoofdpost_omschrijving"]=>
string(8) "value"
}
}
}
Is this somehow possible?
Its better to use direct array assignment rather than using array_push.
In your case, you may only had to replace array_push($arrayTurnover, $arrayYear); and put something like
$arrayTurnover[$amountOfYearsToShow] = $arrayYear;
I hope this will help.

Categories