How to set a value to var in use() method php laravel - php

It seems that I can only read the value from a variable I pass in use($ids) but I can't update the value. How can I change the value?
here is my code
public function show(LPJ $lpj){
$ids = [];
$lpj->request->each(function ($item, $key) use ($ids) {
if ($item->is_submitted) {
return true;
}
if (!$item->form) {
return true;
}
$form = json_decode($item->form, true);
$is_submitted = false;
foreach ($form as $value) {
if (!$value['required']) {
continue;
}
if ($value['value'] === null) {
$is_submitted = false;
break;
}
$is_submitted = true;
}
if ($is_submitted) {
$request_lpj = RequestLPJ::find($item->id);
$request_lpj->is_submitted = true;
$request_lpj->save();
// here I tried to update the $ids
$ids[] = $key;
}
});
}
And it always return an empty array.
How can I pass value to the parent variable?
Thank you

Try Passing by Reference use (&$ids)
$ids = [];
$lpj->request->each(function ($item, $key) use (&$ids) {
if ($item->is_submitted) {
return true;
}
if (!$item->form) {
return true;
}
$form = json_decode($item->form, true);
$is_submitted = false;
foreach ($form as $value) {
if (!$value['required']) {
continue;
}
if ($value['value'] === null) {
$is_submitted = false;
break;
}
$is_submitted = true;
}
if ($is_submitted) {
$request_lpj = RequestLPJ::find($item->id);
$request_lpj->is_submitted = true;
$request_lpj->save();
// here I tried to update the $ids
$ids[] = $key;
}
});

Related

Recursive array map from multidimentional array

I need to build a map of all possibilities from multidimentional array in the following format:
$level['A1']['E1'] = true;
$level['E1']['A1'] = true;
$level['A1']['L1'] = true;
$level['L1']['A1'] = true;
$level['A1']['E2'] = true;
$level['E2']['A1'] = true;
$level['E1']['L1'] = true;
$level['L1']['E1'] = true;
$level['E1']['E2'] = true;
$level['E2']['E1'] = true;
Result needs to have all possible maps in another multidimentional array from A1 to A1, such as:
$level_maps['A1']['E1']['L1']['A1'] = true;
$level_maps['A1']['E1']['E2']['A1'] = true;
$level_maps['A1']['L1']['E1']['A1'] = true;
$level_maps['A1']['L1']['E1']['E2']['A1'] = true;
$level_maps['A1']['E2']['E1']['A1'] = true;
$level_maps['A1']['E2']['E1']['L1']['A1'] = true;
Initial array can be much bigger and I'm having a hard time with a recursive function.
Edit:
I have a simple class with the following function:
private function buildMap(array $levels, $parent) {
$map = array();
foreach ($levels as $level1 => $level2_vals) {
foreach($level2_vals as $level2 => $val) {
if ($parent == $level1) {
$map[$level2] = true;
unset($levels[$level1][$level2]);
$level3 = $this->buildMap($levels, $level2);
if(!empty($level3) && $level2 != $this->end_level) {
$map[$level2] = $level3;
}
else if($level2 != $this->end_level) {
$map[$level2] = false;
}
}
}
}
return $map;
}
calling it with:
$map[$this->start_level] = $this->buildMap($level, $this->start_level);
but it does not work correctly, especially on bigger sets of levels.
Sorry if I am unclear, was just looking for a recursive function example to start with.
Here how it work check the example bellow :
<?php
$level['A1']['E1'] = true;
$level['E1']['A1'] = true;
$level['A1']['L1'] = true;
$level['L1']['A1'] = true;
$level['A1']['E2'] = true;
$level['E2']['A1'] = true;
$level['E1']['L1'] = true;
$level['L1']['E1'] = true;
$level['E1']['E2'] = true;
$level['E2']['E1'] = true;
/// generate array key
$array_keys=array();
foreach($level as $key1 =>$values)
{
foreach($values as $key2 => $values2)
{
$array_keys[]=$key1.'-'.$key2;
}
}
/// split array parent and childrent on diffrent parts
$parent='A1';
$parent_keys=array();
$children_keys=array();
foreach($level as $key =>$val)
{
foreach($val as $key2 =>$val2)
{
if($key == $parent)
$parent_keys[$key.'-'.$key2]=true;
else
$children_keys[$key.'-'.$key2]=true;
}
}
$last_array=array();
foreach($parent_keys as $key =>$va)
{
$exp=explode('-',$key);
foreach($children_keys as $key2 =>$va2)
{
$arrunique=array();
if(!strchr($key2,$exp[1])){
$exp2=explode('-',$key2);
foreach($exp as $r)
{
$arrunique[$r]=$r;
}
foreach($exp2 as $r)
{
$arrunique[$r]=$r;
}
if(in_array($exp[1].'-'.$exp2[0],$array_keys))
$last_array[implode('-',$arrunique).'-'.$exp[0]]=true;
}
}
}
foreach($last_array as $key=>$va)
{
print $key."\n";
}
You can execute from sandbox : LINK

PHP: Getting difference between two multidimensional arrays

I have two arrays like
$a1= array(
array('a'=>1,'b'=>2, 'c'=>3), // similar to $a2[0]
array('a'=>3,'b'=>4, 'c'=>5), // similar to $a2[1]
array('a'=>9,'b'=>6, 'c'=>9)
);
$a2= array(
array('a'=>1,'b'=>2, 'c'=>3),
array('a'=>3,'b'=>4, 'c'=>5),
array('a'=>5,'b'=>6, 'c'=>7),
array('a'=>11,'b'=>4, 'c'=>13),
array('a'=>14,'b'=>6, 'c'=>3)
);
I want a resulting array that does't have common values like
$arrayResult= array(
array('a'=>9,'b'=>6, 'c'=>9),// from $a1[3]
array('a'=>5,'b'=>6, 'c'=>7),// from $a2[2]
array('a'=>11,'b'=>4, 'c'=>13),// from $a2[3]
array('a'=>14,'b'=>6, 'c'=>3)// from $a2[4]
);
I have tried array_udiff, and also separate function but I'm unable to get the right thing.
Hmm fast solution, not optimized
$result = array();
foreach($a1 as $va1) {
$found = false;
foreach($a2 as $va2) {
$x = array_diff($va1, $va2);
if (empty($x)) {
$found = true;
}
}
if (!$found) {
$result[] = $va1;
}
}
foreach($a2 as $va2) {
$found = false;
foreach($a1 as $va1) {
$x = array_diff($va2, $va1);
if (empty($x)) {
$found = true;
}
}
if (!$found) {
$result[] = $va2;
}
}
var_dump($result);
EDIT: A little optimized (unseting values that were found before):
$a1= array(
array('a'=>1,'b'=>2, 'c'=>3), // similar to $a2[0]
array('a'=>3,'b'=>4, 'c'=>5), // similar to $a2[1]
array('a'=>9,'b'=>6, 'c'=>9)
);
$a2= array(
array('a'=>1,'b'=>2, 'c'=>3),
array('a'=>3,'b'=>4, 'c'=>5),
array('a'=>5,'b'=>6, 'c'=>7),
array('a'=>11,'b'=>4, 'c'=>13),
array('a'=>14,'b'=>6, 'c'=>3)
);
$i=0;
$result = array();
foreach($a1 as $ka1 => $va1) {
$found = false;
foreach($a2 as $ka2 => $va2) {
$i++;
$x = array_diff($va1, $va2);
if (empty($x)) {
$found = true;
unset($a2[$ka2], $a1[$ka1]);
}
}
if (!$found) {
$result[] = $va1;
}
}
foreach($a2 as $ka2 => $va2) {
$found = false;
foreach($a1 as $ka1 => $va1) {
$i++;
$x = array_diff($va2, $va1);
if (empty($x)) {
unset($a2[$ka2], $a1[$ka1]);
$found = true;
}
}
if (!$found) {
$result[] = $va2;
}
}
var_dump($result);echo $i;
function check_diff_multi($array1, $array2){
$result = array();
foreach($array1 as $key => $val) {
if(isset($array2[$key])){
if(is_array($val) && is_array($array2[$key])){
$result[$key] = check_diff_multi($val, $array2[$key]);
}
} else {
$result[$key] = $val;
}
}
return $result;
}
//call this function
check_diff_multi($a1,$a2);

merge many array based on a common key php

I wasn't so clear in my first question, so i deleted it and here is a reformulation;
I have those arrays:
$open = array(array("FAI1","34"),array("FAI2","34"),array("FAI3","34"));
$click = array(array("FAI2","52"),array("FAI1","68"),array("FAI3","99"));
$unsubscribe = array(array("FAI2","103"),array("FAI3","67"),array("FAI1","102"));
$def_sent = array(array("FAI1","34",24),array("FAI2","34",23),array("FAI3","34",27));
$SB = array(array("FAI2","103"),array("FAI3","67"),array("FAI1","102"));
$HB = array(array("FAI2","103"),array("FAI3","67"),array("FAI1","102"));
I searched for a function to merge them and get a result like this:
$result = array(array("FAI1",34,68,102,34,24,102,102)
,array("FAI2","34",23.....),
array("FAI3","34",27....));
and to do this, i used the function, in the php online documentation, and this is the function
function array_merge_recursive() {
$arrays = func_get_args();
$base = array_shift($arrays);
foreach ($arrays as $array) {
reset($base);
while (list($key, $value) = #each($array)) {
if (is_array($value) && #is_array($base[$key])) {
$base[$key] = array_merge_recursive($base[$key], $value);
} else {
$base[$key] = $value;
}
}
}
return $base;
}
But instead of getting the result above i got this:
FAI1|34
FAI2|34
FAI3|34
FAI2|52
FAI1|68
FAI3|99
...
So i need some help to reformulate this function to get the expected result.
Try this function:
function array_merge_rec() {
$arrays = func_get_args();
$result = array();
foreach ($arrays as $arg) {
if (is_array($arg)) {
foreach ($arg as $item) {
if (!isset($result[$item[0]])) {
$result[$item[0]] = $item;
} else {
$result[$item[0]][] = $item[1];
}
}
} else {
echo "$arg skippend because it isn't array\n";
}
}
return array_values($result);
}
Does it help?

Remove duplicate values on an array with a condition in PHP

I want to remove some duplicate values on an array, but there is a condition that the script has to ignore the array that contains a specific word.
Below code is adapted from PHP: in_array.
$array = array( 'STK0000100001',
'STK0000100002',
'STK0000100001', //--> This should be remove
'STK0000100001-XXXX', //--> This should be ignored
'STK0000100001-XXXX' ); //--> This should be ignored
$ignore_values = array('-XXXX');
if(make_unique($array, $ignore_values) > 0) {
//ERROR HERE
}
The function to make the array unique is:
function make_unique($array, $ignore) {
$i = 0;
while($values = each($array)) {
if(!in_array($values[1], $ignore)) {
$dupes = array_keys($array, $values[1]);
unset($dupes[0]);
foreach($dupes as $rmv) {
$i++;
}
}
}
return $i;
}
I have tried to use if(!in_array(str_split($values[1]), $ignore)) ... but it just the same.
The array should become like:
STK0000100001
STK0000100002
STK0000100001-XXXX
STK0000100001-XXXX
How to do that?
Try this one, just remove the print_r(); inside the function when using in production
if(make_unique($array, $ignore_values) > 0) {
//ERROR HERE
}
function make_unique($array, $ignore) {
$array_hold = $array;
$ignore_val = array();
$i = 0;
foreach($array as $arr) {
foreach($ignore as $ign) {
if(strpos($arr, $ign)) {
array_push( $ignore_val, $arr);
unset($array_hold[$i]);
break;
}
}
$i++;
}
$unique_one = (array_unique($array_hold));
$unique_one = array_merge($unique_one,$ignore_val);
print_r($unique_one);
return count($array) - count($unique_one);
}
This should work for >= PHP 5.3.
$res = array_reduce($array, function ($res, $val) use ($ignore_values) {
$can_ignore = false;
foreach ($ignore_values as $ignore_val) {
if (substr($val, 0 - strlen($ignore_val)) == $ignore_val) {
$can_ignore = true;
break;
}
}
if ( $can_ignore || ! in_array($val, $res)) {
$res[] = $val;
}
return $res;
}, array()
);
Otherwise
$num_of_duplicates = 0;
$res = array();
foreach ($array as $val) {
$can_ignore = false;
foreach ($ignore_values as $ignore_val) {
if (substr($val, 0 - strlen($ignore_val)) == $ignore_val) {
$num_of_duplicates++;
$can_ignore = true;
break;
}
}
if ( $can_ignore || ! in_array($val, $res)) {
$res[] = $val;
}
}
Edit: Added duplicate count to the second snippet.

How to submit multiple checkbox values?

I want to have multiple values for checkboxes. How do I do that?
It only adds the first option that is selected
<input type="checkbox" name="fields[options]" value="option1[]">option1
<input type="checkbox" name="fields[options]" value="option2[]">option2
<input type="checkbox" name="fields[options]" value="option3[]">option3
There are two PHP files. I will post them below. I am not that experienced with php.
/**************** GOOGLE.DOCS method ************************/
if($_SETTINGS['store_to_gdocs'])
{
include_once("GoogleSpreadsheet/Google_Spreadsheet.php");
$ss = new Google_Spreadsheet($_SETTINGS['gdocs']['user'],$_SETTINGS['gdocs']['password']);
$ss->useSpreadsheet($_SETTINGS['gdocs']['spreadsheet_name']);
$ss->useWorksheet($_SETTINGS['gdocs']['worksheet_name']);
$row = array
(
"Date" => date("m/d/Y H:i"),
);
foreach($_POST['fields'] as $k=>$v)
$row[$k]=$v;
if(!$ss->addRow($row))
$ret['error']=1;
}
Second file
<?php
class Google_Spreadsheet
{
private $client;
private $spreadsheet;
private $spreadsheet_id;
private $worksheet = "Sheet1";
private $worksheet_id;
function __construct($user,$pass,$ss=FALSE,$ws=FALSE)
{
$this->login($user,$pass);
if ($ss) $this->useSpreadsheet($ss);
if ($ws) $this->useWorksheet($ws);
}
function useSpreadsheet($ss,$ws=FALSE)
{
$this->spreadsheet = $ss;
$this->spreadsheet_id = NULL;
if ($ws) $this->useWorksheet($ws);
}
function useWorksheet($ws)
{
$this->worksheet = $ws;
$this->worksheet_id = NULL;
}
function addRow($row)
{
if ($this->client instanceof Zend_Gdata_Spreadsheets)
{
$ss_id = $this->getSpreadsheetId($this->spreadsheet);
if (!$ss_id) throw new Exception('Unable to find spreadsheet by name: "' . $this->spreadsheet . '", confirm the name of the spreadsheet');
$ws_id = $this->getWorksheetId($ss_id,$this->worksheet);
if (!$ws_id) throw new Exception('Unable to find worksheet by name: "' . $this->worksheet . '", confirm the name of the worksheet');
$insert_row = array();
foreach ($row as $k => $v) $insert_row[$this->cleanKey($k)] = $v;
$entry = $this->client->insertRow($insert_row,$ss_id,$ws_id);
if ($entry instanceof Zend_Gdata_Spreadsheets_ListEntry) return TRUE;
}
throw new Exception('Unable to add row to the spreadsheet');
}
// http://code.google.com/apis/spreadsheets/docs/2.0/reference.html#ListParameters
function updateRow($row,$search)
{
if ($this->client instanceof Zend_Gdata_Spreadsheets AND $search)
{
$feed = $this->findRows($search);
if ($feed->entries)
{
foreach($feed->entries as $entry)
{
if ($entry instanceof Zend_Gdata_Spreadsheets_ListEntry)
{
$update_row = array();
$customRow = $entry->getCustom();
foreach ($customRow as $customCol)
{
$update_row[$customCol->getColumnName()] = $customCol->getText();
}
// overwrite with new values
foreach ($row as $k => $v)
{
$update_row[$this->cleanKey($k)] = $v;
}
// update row data, then save
$entry = $this->client->updateRow($entry,$update_row);
if ( ! ($entry instanceof Zend_Gdata_Spreadsheets_ListEntry)) return FALSE;
}
}
return TRUE;
}
}
return FALSE;
}
// http://code.google.com/apis/spreadsheets/docs/2.0/reference.html#ListParameters
function getRows($search=FALSE)
{
$rows = array();
if ($this->client instanceof Zend_Gdata_Spreadsheets)
{
$feed = $this->findRows($search);
if ($feed->entries)
{
foreach($feed->entries as $entry)
{
if ($entry instanceof Zend_Gdata_Spreadsheets_ListEntry)
{
$row = array();
$customRow = $entry->getCustom();
foreach ($customRow as $customCol)
{
$row[$customCol->getColumnName()] = $customCol->getText();
}
$rows[] = $row;
}
}
}
}
return $rows;
}
// user contribution by dmon (6/10/2009)
function deleteRow($search)
{
if ($this->client instanceof Zend_Gdata_Spreadsheets AND $search)
{
$feed = $this->findRows($search);
if ($feed->entries)
{
foreach($feed->entries as $entry)
{
if ($entry instanceof Zend_Gdata_Spreadsheets_ListEntry)
{
$this->client->deleteRow($entry);
if ( ! ($entry instanceof Zend_Gdata_Spreadsheets_ListEntry)) return FALSE;
}
}
return TRUE;
}
}
return FALSE;
}
function getColumnNames()
{
$query = new Zend_Gdata_Spreadsheets_ListQuery();
$query->setSpreadsheetKey($this->getSpreadsheetId());
$query->setWorksheetId($this->getWorksheetId());
$query->setMaxResults(1);
$query->setStartIndex(1);
$feed = $this->client->getListFeed($query);
$data = array();
if ($feed->entries)
{
foreach($feed->entries as $entry)
{
if ($entry instanceof Zend_Gdata_Spreadsheets_ListEntry)
{
$customRow = $entry->getCustom();
foreach ($customRow as $customCol)
{
array_push($data,$customCol->getColumnName());
}
}
}
}
return $data;
}
private function login($user,$pass)
{
// Zend Gdata package required
// http://framework.zend.com/download/gdata
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Http_Client');
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Spreadsheets');
$service = Zend_Gdata_Spreadsheets::AUTH_SERVICE_NAME;
$http = Zend_Gdata_ClientLogin::getHttpClient($user,$pass,$service);
$this->client = new Zend_Gdata_Spreadsheets($http);
if ($this->client instanceof Zend_Gdata_Spreadsheets) return TRUE;
return FALSE;
}
private function findRows($search=FALSE)
{
$query = new Zend_Gdata_Spreadsheets_ListQuery();
$query->setSpreadsheetKey($this->getSpreadsheetId());
$query->setWorksheetId($this->getWorksheetId());
if ($search) $query->setSpreadsheetQuery($search);
$feed = $this->client->getListFeed($query);
return $feed;
}
private function getSpreadsheetId($ss=FALSE)
{
if ($this->spreadsheet_id) return $this->spreadsheet_id;
$ss = $ss?$ss:$this->spreadsheet;
$ss_id = FALSE;
$feed = $this->client->getSpreadsheetFeed();
foreach($feed->entries as $entry)
{
if ($entry->title->text == $ss)
{
$ss_id = array_pop(explode("/",$entry->id->text));
$this->spreadsheet_id = $ss_id;
break;
}
}
return $ss_id;
}
private function getWorksheetId($ss_id=FALSE,$ws=FALSE)
{
if ($this->worksheet_id) return $this->worksheet_id;
$ss_id = $ss_id?$ss_id:$this->spreadsheet_id;
$ws = $ws?$ws:$this->worksheet;
$wk_id = FALSE;
if ($ss_id AND $ws)
{
$query = new Zend_Gdata_Spreadsheets_DocumentQuery();
$query->setSpreadsheetKey($ss_id);
$feed = $this->client->getWorksheetFeed($query);
foreach($feed->entries as $entry)
{
if ($entry->title->text == $ws)
{
$wk_id = array_pop(explode("/",$entry->id->text));
$this->worksheet_id = $wk_id;
break;
}
}
}
return $wk_id;
}
function cleanKey($k)
{
return strtolower(preg_replace('/[^A-Za-z0-9\-\.]+/','',$k));
}
}
Thank you for helping!
You have your checkbox names and values mixed up. It should be:
<input type="checkbox" name="fields[options][]" value="option1">option1
<input type="checkbox" name="fields[options][]" value="option2">option2
<input type="checkbox" name="fields[options][]" value="option3">option3
Now you can manipulate $_POST['fields']['options'] like so:
$options = (is_array($_POST['fields']['options'])) ? $_POST['fields']['options'] : array();
Then you can implode them:
$options_string = implode(',', $options) // will return option1,option2,option3 etc
or loop through them:
foreach ($options as $option)
{
echo $option.'<br>';
}
// produces option1<br>option2<br>option3 etc
Don't give the name a key in the array - it should be set to name="fields[]".
See this post.

Categories