Array check if object key has same value - arrays

I want to push values from old array to a new array. when pushing I am checking the object value is already exist or not. the value should be pushed only when the same object value is not exist in new array. here is my code.
$sorted_array = array();
foreach ($data as $nkey => $value) {
if (count($sorted_array) > 0) {
dd($sorted_array[$nkey]);
if ($sorted_array[$nkey]['store'] != $value['store']) {
array_push($sorted_array, $value);
}
}
else{
array_push($sorted_array, $value);
}
}

If I understood correctly, you can easily handle it using the in_array function:
$sorted_array = array();
foreach ($data as $nkey => $value) {
if ( !in_array($value, $sorted_array) ) {
array_push($sorted_array, $value);
}
}
in_array function return boolean value. In my code, if the $value parameter is not in the $sorted_array, then it will pushed. Otherwise operation is not performed.

array_push in this case is wrong.
Try this code:
foreach ($data as $nkey => $value) {
if (count($sorted_array) > 0) {
if ($sorted_array[$nkey]['store'] != $value['store']) {
$sorted_array[$nkey] = $value;
}
}
}
Hope can help you

Related

Get array object data from exploded array fields in foreach loop

I'm trying to extract data from our JSON data based on given output fields, but I'm not getting a good result.
e.g.
Given fields that I want:
Array
(
[0] => id
[1] => name
[2] => email
[3] => optin_email
)
Those fields exist in my datastring, I want to export those to a CSV.
I can do this, hardcoded
foreach ($jsonString as $value) {
$row = [
$value->id,
$value->name,
$value->email,
$value->phone
];
print_r($row);
}
The above will give me the list/file I need. BUT, I want to make that dynamic based on the data in the array, so, fo rexample, when this is the Array:
Array
(
[0] => id
[1] => name
)
This should be my output:
foreach ($jsonString as $value) {
$row = [
$value->id,
$value->name
];
print_r($row);
}
So I need to dynamicly create the
$value->{var}
I have been trying forever, but I am not seeing it straight anymore.
Tried this:
$rowFields = '';
foreach ($export_datafields AS $v) {
$rowFields .= '$value->' . $v . ',';
}
$trimmed_row_fields = rtrim($rowFields, ',');
foreach ($jsonString as $value) {
$row = $trimmed_row_fields;
print_r($row);
}
And several variations of that:
foreach ($jsonString as $value) {
$row = [$trimmed_row_fields];
print_r($row);
}
Question is: how can I get
$value->VAR
as a valid array key when I only know the VAR name and need the prefixed $value-> object.
I ended up using the following code which works for me. If anybody still has the answer to my original question, please shoot. Always good to know it all.
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=$csvFileName");
header("Pragma: no-cache");
header("Expires: 0");
$new_row = implode(",", $export_datafields) . "\n";
foreach ($jsonString as $value) {
foreach ($export_datafields AS $v) {
$new_row .= $value->$v . ',';
}
$new_row = substr($new_row, 0, -1);
$new_row .= "\n";
}
echo $new_row;

CakePHP 3: exclude vendor tables when getting a list of all table objects

in my database, I have tables created by some plugins. I need to show only my models in a dropdown list.
in bootstrap.php:
Configure::write('ReportManager.modelIgnoreList',array(
'acl_phinxlog',
'acos',
'aros',
'aros_acos',
'audits',
'burzum_file_storage_phinxlog',
'burzum_user_tools_phinxlog',
'cake_d_c_users_phinxlog',
'file_storage',
'phinxlog',
));
In my controller index function:
if (empty($this->data)) {
$modelIgnoreList = Configure::read('ReportManager.modelIgnoreList');
$models = ConnectionManager::get('default')->schemaCollection()->listTables();
foreach($models as $key => $model) {
if ( isset($modelIgnoreList) && is_array($modelIgnoreList)) {
foreach ($modelIgnoreList as $ignore) {
if (isset($models[$ignore])) {
unset($models[$ignore]);
$modelData = TableRegistry::get($model);
debug($modelData);
}
}
}
}
debug($modelIgnoreList);
}
In index.ctp:
echo $this->Form->create('ReportManager');
echo '<fieldset>';
echo '<legend>' . __d('report_manager','New report',true) . '</legend>';
echo $this->Form->input('model',array(
'type'=>'select',
'label'=>__d('report_manager','Model',true),
'options'=>$models,
'empty'=>__d('report_manager','--Select--',true)
));
My result keeps showing all the tables. Where is my mistake ?
You are calling unset using the model name, not the key. Also, you don't need two foreach loops here.
$models = ConnectionManager::get('default')->schemaCollection()->listTables();
if (isset($modelIgnoreList) && is_array($modelIgnoreList)) {
foreach($models as $key => $model) {
if (in_array($model, $modelIgnoreList)) {
unset($models[$key]);
}
}
}
Or, even simpler, use the built-in functionality to handle this for you:
$models = ConnectionManager::get('default')->schemaCollection()->listTables();
if (isset($modelIgnoreList) && is_array($modelIgnoreList)) {
$models = array_diff($models, $modelIgnoreList);
}

Wordpress use array key and value to set data attribute

I have setup an array of product values. I need to set each array key to the data-attribute and the value to the data-attribute value
<li data-name="product1" data-price="49.99" data-rating="4.5"></li>
So in Wordpress I have this filter hook
function product_data_sorting( $product_attrs, $product, $terms) {
global $post;
// Product Attributes
$product_attrs['name'] = $post->post_name;
$product_attrs['price'] = $product->price;
$product_attrs['rating'] = $product->get_average_rating();
$product_attrs['newness'] = $post->post_modified;
// Product Categories
foreach ($terms as $term) {
$categories[] = $term->slug;
}
$product_attrs['categories'] = $categories;
foreach ($product_attrs as $attribute) {
if ( is_array($attribute) ) {
//This is a category
}
else {
$results[] = 'data-' . $key . '="' . '$attribute' . '"';
}
}
return $results
}
add_filter( 'add_sorting', 'product_data_sorting', 10, 3 );
I am getting all the correct data pushed in to the $product_attrs array that I need, but not sure how to work with the array key and values so that in the $results array it would be formatted like this:
$results = (data-name="product1", data-price="49.99", data-rating="4.5");
Hope that makes some sense
thanks
You would need key=>value pair within foreach.
$ignored = array ('newness'); // array to maintain what attributes you want to ignore
foreach ($product_attrs as $key => $attribute) {
if ( is_array($attribute) ) {
//This is a category
}
else {
if(!inarray($key, $ignored)
$results[] = 'data-' . $key . '="' . $attribute . '"';
}
}
Also note that $attribute isn't enlcosed in single quotes as you have in the question. Variables inside single quote can not be parsed

how to check the value of an array in codeigniter

$result=array();
$count = count($days);
for($i=0;$i<$count-1; $i++)
{
$bookDate = $days[$i];
$fromDate = $this->booking_model->Get_BookedDate($bookDate,$roomname);
if ($fromDate != 0)
{
$result[] = $bookDate;
}
}
return $result;
This is my codeigniter controller function here I want to check the value of $fromDate is zero or not. I am getting the array like this
Array ( [0] => Array ( ["2013-04-27" between fromDate and toDate] => 1 ) )
I am very new to codeigniter. Thank you for any help.
$result=array();
$count = count($days);
for($i=0;$i<$count-1; $i++)
{
$bookDate = $days[$i];
$fromDate = $this->booking_model->Get_BookedDate($bookDate,$roomname);
if (!empty($fromDate[0]['"'.$bookDate.'" between fromDate and toDate']))
{
$result[] =$bookDate;
}
}
return $result;
Try this.IT may help you
Make use of empty() function.
if(!empty($fromdate)) { //if $formdate is empty or 0 or false the loop won't be executed
//Your code.
}
if (!empty($fromDate))
{
$result[] = $bookDate;
}
Try this.

update Auth session

How to update user information stored in auth session? without logout and login again.
I think this function will do it.. but is it the best-practice?
function update($field, $value){
$this->Session->write($this->Auth->sessionKey . '.' . $field, $value);
}
Yes.
You could grab the current info array, modify it, and then call $this->Auth->login($newUserData);, but this will also renew the session (no user interaction needed, though). Note: Applies to CakePHP 2.0+ only.
I've completed update function to get an array of new values. with keys (field name):
public function update($fields, $values = null) {
if (empty(parent::$_user) && !CakeSession::check(parent::$sessionKey)) {
return false;
}
if (!empty(parent::$_user)) {
$user = parent::$_user;
} else {
$user = CakeSession::read(parent::$sessionKey);
}
if (is_array($fields)) {
if (is_array($values)) {
$data = array_combine($fields, $values);
} else {
$data = $fields;
}
} else {
$data = array($fields => $values);
}
foreach ($data as $field => $value) {
if (isset($user[$field])) {
$user[$field] = $value;
}
}
return $this->login($user);
}
(thanks to tigrang for login function)

Resources