PHP array serialize key value CodeIgniter cache - php

I have table name 'preferences' column(key,value)
I use cache in codeigniter
look this :
$pref = $this->ci->db->get('preferences')->result();
$this->ci->cache->save('preferences', $pref, 30000);
save cache :
a:3:{s:4:"time";i:1386246188;s:3:"ttl";i:30000;s:4:"data";a:87:{i:0;O:8:"stdClass":2:{s:3:"key";s:10:"site_title";s:5:"value";s:13:"CARS Big";}i:1;O:8:"stdClass":2:{s:3:"key";s:11:"forum_title";s:5:"value";s:14:"CARS Big forum";}i:2;O:8:"stdClass":2:{s:3:"key";s:14:"forum_per_page";s:5:"value";s:2:"10";}...
Call cache use:
$data = $this->ci->cache->get('preferences');
print_r($data);
output:
Array(
[0] => Array
(
[key] => site_title
[value] => CARS Big
)
[1] => Array
(
[key] => forum_title
[value] => CARS Big forum
)
[2] => Array
(
[key] => forum_per_page
[value] => 10
)
[3] => Array
(
[key] => forum_section_per_page
[value] => 10
)
[4] => Array
(
[key] => forum_replies_per_page
[value] => 5
)
[5] => Array
(
[key] => forum_can_add_pictures
[value] => 1
)
[6] => Array
(
[key] => forum_can_add_poll
[value] => 1
)
[7] => Array
(
[key] => forum_can_set_time_to_close
[value] => 1
)
[8] => Array
(
[key] => forum_can_set_replies_to_close
[value] => 1
)
[9] => Array
(
[key] => forum_auto_active_topics
[value] => 1
)
[10] => Array
(
[key] => market_title
[value] => market CARS Big
)
[11] => Array
(
[key] => market_per_page
[value] => 5
)
[12] => Array
(
[key] => market_section_per_page
[value] => 3
)
)
How do I make the content of the column key is the key
And the column value is the content
Like this:
$data['site_title']
I need $data['site_title'] to print : CARS Big
so as to call this function
function pref($key=NULL)
{
$data = $this->ci->cache->get('preferences');
return $data[$key];
}
**

Essentially you are looking to loop the values and re-assign the keys so something like this could work:
// loop through data
foreach($data as $k=>$v)
{
// unset the original array item to get rid of $data[0], $data[1], $data[2] as so forth
unset($data[$k]);
// $k is a digit (0,1,2,3,4,5,....)
// $v is the array of values so $v['key'] is 'site_title' and $v['value'] is 'CARS Big'
// so essentially we are doing $data['site_title'] = 'CARS Big'; in the line below
$data[$v['key']] = $v['value'];
}

you can't, since the cache save implementation is a fixed process. only if you make your own cache implementation.
but you can perform your return function like this
function pref($key=NULL)
{
// call pref data
$data = $this->ci->cache->get('preferences');
if( ! $data ) {
// cache not present request new
$data = $this->ci->db->get('preferences')->result();
$this->ci->cache->save('preferences', $data, 30000);
}
// loop
foreach( $data as $preferences ) {
if( isset( $preferences['key'] ) && $preferences['key'] == $key ){
return $preferences['value'];
}
}
return false;
}

Related

Get Array in foreach loop from string

I have an Array of Strings, each String that exist in Advanced Custom Fields groups should be returned in foreach loop. Final results should be a single array of all values.
$lubuvna_groups = acf_get_field_groups();
$ArrayDiffs = array_diff($resultsFilesKey, $resultsKey);
foreach($ArrayDiffs as $ArrayDiff) {
$resultsFileToImports[] = $ArrayDiff;
}
//$keysToImports = implode(", ",$resultsFileToImports);
$keysToImports = 'group_lubuvna_contact, group_lubuvna_subscriber';
foreach($resultsFileToImports as $resultsFileToImportsKey) {
$keysToImports_filtered = array_filter($lubuvna_groups, function($el) use ($keysToImports) {
return ( strpos($el['key'], $keysToImports) !== false );
});
}
The above code returns only if one string exists in $keysToImports. Once there are more than one value it doesn't work. I am sure i am missing something, but can't find any solution in here!
It shows me empty Array:
Array ( )
Maybe there is a different way how to get the arrays without strpos?
Final Array should looks like following:
Array ( [0] => Array ( [ID] => 0 [key] => group_lubuvna_contact [title] => ACF Fields [fields] => Array ( ) [location] => Array ( [0] => Array ( [0] => Array ( [param] => post_type [operator] => == [value] => page ) ) ) [menu_order] => 0 [position] => normal [style] => default [label_placement] => top [instruction_placement] => label [hide_on_screen] => [active] => 1 [description] => [local] => json [modified] => 1592781382 [_valid] => 1 ) [1] => Array ( [ID] => 0 [key] => group_lubuvna_subscriber [title] => Lubuvna - Subscriber Fields [fields] => Array ( ) [location] => Array ( [0] => Array ( [0] => Array ( [param] => post_type [operator] => == [value] => post ) ) [1] => Array ( [0] => Array ( [param] => post_type [operator] => == [value] => page ) ) [2] => Array ( [0] => Array ( [param] => post_type [operator] => == [value] => lubuvna_subscriber ) ) ) [menu_order] => 0 [position] => normal [style] => default [label_placement] => top [instruction_placement] => label [hide_on_screen] => [active] => 1 [description] => [local] => json [modified] => 1592781369 [_valid] => 1 ) )
Try changing:
$keysToImports = 'group_lubuvna_contact', 'group_lubuvna_subscriber';
// then return
return ( strpos($el['key'], $keysToImports) !== false );
to
$keysToImports = ['group_lubuvna_contact', 'group_lubuvna_subscriber'];
// then return
return in_array($el['key'], $keysToImports);
Full code update:
$lubuvna_groups = acf_get_field_groups();
$ArrayDiffs = array_diff($resultsFilesKey, $resultsKey);
foreach($ArrayDiffs as $ArrayDiff) {
$resultsFileToImports[] = $ArrayDiff;
}
$keysToImports = ['group_lubuvna_contact', 'group_lubuvna_subscriber'];
foreach($resultsFileToImports as $resultsFileToImportsKey) {
$keysToImports_filtered = array_filter($lubuvna_groups, function($el) use ($keysToImports) {
return in_array($el['key'], $keysToImports);
});
}

Unset data based on key match

data
Array
(
[0] => Array
(
[id] => 9962
[value] => Amart
)
[1] => Array
(
[id] => attrval_9962
[value] => k
)
[2] => Array
(
[id] => 9952
[value] => Denim
)
[3] => Array
(
[id] => attrval_9952
[value] => l
)
[4] => Array
(
[id] => 5788
[value] => Grey
)
[5] => Array
(
[id] => 21307
[value] => Long Sleeve
)
)
Above is the data that store in array, anyone know how to unset the data if the attrval_ exist so that i want to unset the data id 9962. so the data will look like below.
Array
(
[0] => Array
(
[id] => attrval_9962
[value] => k
)
[1] => Array
(
[id] => attrval_9952
[value] => l
)
[2] => Array
(
[id] => 5788
[value] => Grey
)
[3] => Array
(
[id] => 21307
[value] => Long Sleeve
)
)
Which mean that I only want to store the data which is attrval_ exists else will store back the default value.
First get an Array which contain
$filtered = array_filter($data, function($element){
return strpos($element['id'], 'attrval_') !== false;
});
Then find the difference of both array.
$result = array_udiff($data, $filtered, function($a, $b) {
return intval($a != $b);
});
You can do it with
$result = [];
foreach(data as $value){
if(strpos($value['id'],'attrval_) !== false){
$result[] = $value
}
}
$filtered = array_filter($array, function ($data) {
return strpos($data['id'], 'attrval_') !== false;
});

Searching in array return wrong result

I have received array like this
Array
(
[hash] => 9761d3233f9cb256c0992be
[total] => 2736712601
[received] => 2017-01-13T21:43:32.047Z
[income] => Array
(
[0] => Array
(
[value] => 647262
[addresses] => Array
(
[0] => Address_1
)
)
[1] => Array
(
[value] => 17200000
[addresses] => Array
(
[0] => Address_2
)
)
[2] => Array
(
[value] => 3729034
[addresses] => Array
(
[0] => Address_3
)
)
[3] => Array
(
[value] => 2414997500
[addresses] => Array
(
[0] => Address_4
)
)
[4] => Array
(
[value] => 10856454
[addresses] => Array
(
[0] => Address_5
)
)
)
)
So in my database I store the hash (9761d3233f9cb256c0992be). The I hash and the address. Then based on them I match the correct array from [income]. When I found correct address in income I take the [value] and showing it on the page. Here is how I've made it
$url=get_curl_content("https://example.com/".$order->hash);
$totala =json_decode($url,true);
....
$match = true;
foreach ($totala['income'] as $data) {
if ($data['addresses'] == $order->address) {
$match = $data;
break;
}
}
$price = $data['value'];
The problem is that I'm expecting Address_2 because in database i have saved Address_2 I've got Address_3 instead.
When I var_dump($data['addresses']) i got Address_3. What can be the problem?
Try like this. It will search and match in array using in_array function
$match = true;
foreach ($totala['income'] as $data) {
if (in_array($order->address, $data['addresses'])) {
$match = $data;
break;
}
}
$price = $match['value'];

PHP delete array index through value

I'm trying to unset two specific array positions which contain two values.
My actual code to fill the array.
function get_store_list(){
$data = #file_get_contents('http://www.zwinky.com/xml/clothingList.xml');
$data = #simplexml_load_string($data);
$data = $data->xpath('//stores/store');
foreach($data as $store) {
$storeArray[] = array(
"name" => (string)$store['name'],
"id" => (string)$store['id']
);
}
return $storeArray;
}
$store = get_store_list();
The array looks like the following incase ill echo it out using print_r function:
Array
(
[0] => Array
(
[name] => Artizans
[id] => 20037336
)
[1] => Array
(
[name] => Bwabies!
[id] => 20080134
)
[2] => Array
(
[name] => Crave Mart
[id] => 20097365
)
[3] => Array
(
[name] => David & Goliath
[id] => 20099998
)
[4] => Array
(
[name] => Domo
[id] => 20098166
)
[5] => Array
(
[name] => Emily the Strange
[id] => 20101926
)
[6] => Array
(
[name] => Garfield
[id] => 20098167
)
[7] => Array
(
[name] => Jetsetter
[id] => 26
)
[8] => Array
(
[name] => Like Dat
[id] => 3
)
[9] => Array
(
[name] => Paris Hilton
[id] => 21
)
[10] => Array
(
[name] => Peppermint Place
[id] => 12
)
[11] => Array
(
[name] => Rocawear
[id] => 19
)
[12] => Array
(
[name] => ShoeBuy
[id] => 10
)
[13] => Array
(
[name] => Skelanimals
[id] => 20100198
)
[14] => Array
(
[name] => Snoop Dogg
[id] => 20
)
[15] => Array
(
[name] => SW&TH
[id] => 20096121
)
[16] => Array
(
[name] => The Castle
[id] => 1
)
[17] => Array
(
[name] => The Lair
[id] => 4
)
[18] => Array
(
[name] => The Mix
[id] => 923
)
[19] => Array
(
[name] => The Powerpuff Girls
[id] => 20098121
)
[20] => Array
(
[name] => The Surf Shop
[id] => 5
)
[21] => Array
(
[name] => Tie The Knot
[id] => 20076231
)
[22] => Array
(
[name] => tokidoki
[id] => 20099224
)
[23] => Array
(
[name] => University Club
[id] => 2
)
[24] => Array
(
[name] => Z Avenue
[id] => 6
)
[25] => Array
(
[name] => Z's Greetings
[id] => 20099506
)
)
Now $store does contain 2 array indexes which I have to delete. Which are the following ids: 21 and 20076231
I've been trying the following already:
Array search code without beeing success. Does anyone have a idea what I could try?
There are a handful different approaches for this simple issue. One of them could be using function array_filter():
/**
* #param array $list the list to process
* #param array $IDsToRemove the IDs of elements to remove from $list
* #return array a subset of $list that does not contain elements having 'id' in $IDsToRemove
*/
function removeFromArray(array $list, array $IDsToRemove)
{
return array_filter(
// Filter the input list...
$list,
// ... using a function...
function (array $item) use ($IDsToRemove) {
// ... that accepts an element if its "id" is not in $IDsToRemove
return ! in_array($item['id'], $IDsToRemove);
}
);
}
// Usage
$filteredStore = removeFromArray($store, array(21, 20076231));
Try this in your loop, this will not include in your array than no need to unset like this:
foreach($data as $store) {
if($store['id'] == '20076231')
continue;
$storeArray[] = array(
"name" => (string)$store['name'],
"id" => (string)$store['id']
);
}
If you need to unset an item from your array after it's been created, take a look at array_map.
First map your array to retrieve the index of each ID.
$map = array_map(function($item){ return $item['id']; }, $store);
Then get the index of your ID from the map (e.g. 21).
$index = array_search(21, $map);
Then remove with array_splice.
array_splice($store, $index, 1);
why not use directly the id in your $storeArray? And as it seems to be integer why do you force it to (string)?
Try this:
function get_store_list(){
$data = #file_get_contents('http://www.zwinky.com/xml/clothingList.xml');
$data = #simplexml_load_string($data);
$data = $data->xpath('//stores/store');
foreach($data as $store) {
$storeArray[(int)$store['id']] = array(
"name" => (string)$store['name']
);
}
return $storeArray;
}
// delete the keys you want
unset ($storeArray[21], $storeArray[20076231]);
// or if you have more ids to delete you can create a deleteArray
$deleteArray = array(2, 20076231);
foreach ($deleteArray as $toDelete){
unset($storeArray($toDelete);
}
One line code is cool but sometimes explicit code is preferable.
function filter_by_id(array $data, $id)
{
foreach ($data as $k => &$v) {
foreach ((array) $id as $i) {
if ($v['id'] === $i) {
$v = null;
}
}
}
// 'array_filter()' produces a new array without the null entries.
// 'array_values()' produces a new array with indexes without gaps.
return array_values(array_filter($data));
}
You can filter by one id at time
$store = filter_by_id($store, 21);
Or you can filter multiple ids at the same time:
$store = filter_by_id($store, [21, 20076231]);

PHP - Merge 2 arrays of object using a key/id

I want to merge the 2 arrays of objects based on the 'id' field of Array1 and the 'itemVendorCode' of Array2. I also wanted to remove from the resulting arrays of object anything that didn't match.
Array1:
Array
(
[0] => stdClass Object
(
[id] => 10-423-1176
[qty] => 2
[price] => 12.6
)
[1] => stdClass Object
(
[id] => 89-575-2354
[qty] => 24
[price] => 230.35
)
[2] => stdClass Object
(
[id] => 89-605-1250
[qty] => 2
[price] => 230.35
)
)
Array2:
Array
(
[0] => Item Object
(
[internalId] => 14062
[itemVendorCode] => 89-605-1250
)
[1] => Item Object
(
[internalId] => 33806
[itemVendorCode] => 89-575-2354
)
[2] => Item Object
(
[internalId] => 64126
[itemVendorCode] => 26-295-1006
)
)
I was able to solve this by this code:
$indexed = array();
foreach($itemsArray as $value) {
$indexed[$value->itemVendorCode] = $value;
}
$results = array();
foreach($vendorItems as $obj) {
$value = $indexed[$obj->id];
if (isset($value)) {
foreach($value as $name => $val) {
$obj->$name = $val;
array_push($results, $obj);
}
}
}
print_r($results);
credits to the original poster. I just modified it a bit,
I was able to get the result like this:
Array
(
[0] => stdClass Object
(
[id] => 10-423-1176
[qty] => 2
[price] => 12.6
[internalId] => 2035
[itemVendorCode] => 10-423-1176
)
[1] => stdClass Object
(
[id] => 10-423-1176
[qty] => 2
[price] => 12.6
[internalId] => 2035
[itemVendorCode] => 10-423-1176
)
[2] => stdClass Object
(
[id] => 14-102-1010
[qty] => 16
[price] => 3.2
[internalId] => 57033
[itemVendorCode] => 14-102-1010
)
)
I think you will have to use array_map function which provides you a callback function to execute on array(s).
In the callback function:
- declare your array1
- foreach the second array
- set an if statement to check that the current iteration with the id value matches the itemVendorCode of the array2 and return it
something like this:
// You have to specify to PHP to use a local copy of your $array2 to works with it into your callback
$cb = function ($obj1) use ($array2)
{
// you foreach this array
foreach ($array2 as $obj2) {
// if the value of id matches itemVendorCode
if ($obj1->id === $obj2->itemVendorCode) {
// you return the id
return $obj->id;
}
}
};
// this function will fill a new array with all returned data
$mergedArray = array_map($cb, $array1);
This code is a sample but doesn't provide you, your needled solution, try to update it to do what you exactly want ;)

Categories