I have the following testcode.
Now its a very smal array, but in realtime very large.
How can i update only the values from key 1 direct in the APC FOO?
$test = array(
array(
'name' => 'Mike',
'lastname' => 'Last',
),
array(
'name' => 'test',
'lastname' => 'testlast',
),
array(
'name' => 'anothertest',
'lastname' => 'anothertestlast',
),
);
apc_store('foo', $test);
print_r(apc_fetch('foo'));
I don't think you can alter the variable directly in the cache. My best guess would be to write a function which gets the data from the cache, alters it, and stores it back in the cache. Maybe something like:
function apc_update_array($cacheKey, $arrayKey, $array)
{
$data = apc_fetch($cacheKey);
$data[$arrayKey] = $array;
apc_store($cacheKey, $data);
}
With that function you could just run the following code to get it done.
apc_update_array(
'foo',
1,
array(
'name' => 'differenttest',
'lastname' => 'differenttestlast',
)
);
Related
This question already has answers here:
PHP is there a way to add elements calling a function from inside of array
(3 answers)
Closed last month.
In the middle of declaring an array of arrays, I want to "write" an array of arrays generated by my function.
I have a working example when I:
simply store my function-generated arrays into a variable and
then call each array from that function by its key,
but I can't find a command to simply call everything at once.
Here is the code which (I hope) explains it:
<?php
// A. (THIS WORKS)
// A1: A function that returns an array of arrays
function my_arrays_building_function() {
$first_array = array(
'id' => 'my_array_1',
'type' => 'some-type',
'title' => 'My title 1',
);
$second_array = array(
'id' => 'my_array_2',
'type' => 'some-type',
'title' => 'My title 2',
);
// ... and so on, many more.
return array(
'first-array' => $first_array,
'second-array' => $second_array,
// ... and so on.
);
// NOTE there are tens or hundreds of returned arrays here.
}
// A2: Store my arrays in a variable
$my_array = my_arrays_building_function();
// A3: Inside an array (of arrays), I simply "write" my arrays INDIVIDUALLY and THAT works
array(
array(
'id' => 'dummy_preexisting_array_1',
'type' => 'some-type',
),
array(
'id' => 'dummy_preexisting_array_2',
'type' => 'some-type',
),
// HERE THERY ARE, INDIVIDUALLY, COMMA SEPARATED
$my_array[ 'first-array' ],
$my_array[ 'second-array' ],
array(
'id' => 'dummy_preexisting_array_n',
'type' => 'some-type',
)
),
/** -------------------- //
THE ISSUE
// -------------------- **/
// B: HOW DO I "write" THEM ALL AT ONCE???
// B1: The same as A1
function my_arrays_building_function() {
$first_array = array(
'id' => 'my_array_1',
'type' => 'some-type',
'title' => 'My title 1',
);
$second_array = array(
'id' => 'my_array_2',
'type' => 'some-type',
'title' => 'My title 2',
);
// NOT SURE I SHOULD RETURN LIKE THIS
return array(
'first-array' => $first_array,
'second-array' => $second_array
);
}
// B2: Same as A3, Inside an array (of arrays), I "write" my arrays BUT NOW I WANT TO "WRITE" THEM ALL AT ONCE
array(
array(
'id' => 'dummy_preexisting_array_1',
'type' => 'some-type',
),
array(
'id' => 'dummy_preexisting_array_2',
'type' => 'some-type',
),
/** >>>> I need my arrays here ALL AT ONCE aka NOT INDIVIDUALLY AS IN EXAMPLE A. <<<< **/
/**
* In other words, while I'm declaring this array,
* I simply need all my arrays from my_arrays_building_function()
* "written" here with a simple command instead of calling hundreds
* of arrays individually as in the first example
*/
array(
'id' => 'dummy_preexisting_array_n',
'type' => 'some-type',
)
), /* this goes on as it's a part of even bigger array */
Although I wouldn't recommend declaring hundreds of array variables inside a function because that's crazy, but for now, you can use get_defined_vars() to get over this issue.
You will also need to filter out the variables which are arrays and has the keys id, type and title as there are could be several other variables defined apart from this.
Snippet:
<?php
array_filter(get_defined_vars(), fn($val) => is_array($val) && isset($val['id'], $val['type'], $val['title']));
Online Demo
Not too sure if I'm understanding this correctly but from what I assume, you just want to return an array with a bunch of others inside it that you define throughout the function?
A simple approach for this would be to define your output variable immediately and add all of your other arrays to it:
function my_arrays_building_function() {
$output = [];
$output[] = [
'id' => 'my_array_1',
'type' => 'some-type',
'title' => 'My title 1',
];
$output[] = [
'id' => 'my_array_2',
'type' => 'some-type',
'title' => 'My title 2',
];
return $output;
}
Thank you to #Rylee for suggesting Array Unpacking.
The final code would look like this:
// C1: A function that returns an array of arrays BUT without keys
function my_arrays_building_function() {
$first_array = array(
'id' => 'my_array_1',
'type' => 'some-type',
'title' => 'My title 1',
);
$second_array = array(
'id' => 'my_array_2',
'type' => 'some-type',
'title' => 'My title 2',
);
// ... and so on, many more.
// Then return but now I don't assign keys, I only list the vars.
return array(
$first_array, $second_array, ... and so on.
);
}
// C2: Inside an array (of arrays), I use Array Unpacking, THAT'S WHAT I WAS LOOKING FOR, UNPACK ARRAY! SEE BELOW
array(
array(
'id' => 'dummy_preexisting_array_1',
'type' => 'some-type',
),
array(
'id' => 'dummy_preexisting_array_2',
'type' => 'some-type',
),
// HERE I UNPACK MY ARRAY BY USING ... THE THREE DOTS ARE THE KEY
... my_arrays_building_function(),
array(
'id' => 'dummy_preexisting_array_n',
'type' => 'some-type',
)
),
Hooray!
Consider the following array:
$serviceNames = array(
0 => array(
'language' => 'en',
'value' => 'something',
'type' => 'name',
),
1 => array(
'language' => 'fi',
'value' => 'jotain',
'type' => 'name',
),
2 => array(
'language' => 'sv',
'value' => 'någonting',
'type' => 'name',
),
);
I need to get the 'value' definitions based on language. The problematic part is that the array $serviceNames does not have a predefined length (comes originally as a JSON file from an API), and the items can come in any order (in my example it goes like en, fi, sv, but it could be de, en, sv, fr... you get it).
If I wanted to get 'value' within the array where 'language' equals to 'en', how could I do that?
My advice is that you make the array associative.
Once that is done you access the value by ["language"]["value"].
$serviceNames = array_column($serviceNames, Null, "language");
echo $serviceNames["fi"]["value"]; //jotain
echo $serviceNames["en"]["value"]; //something
echo $serviceNames["sv"]["value"]; //någonting
https://3v4l.org/ssGQa
You can array_search() and array_column() function. first find the key where "en" is in the array then get the value.
$key = array_search('en', array_column($serviceNames, 'language'));
echo $serviceNames[$key]['value'];
Demo
simple:
$serviceNames = array(
0 => array(
'language' => 'en',
'value' => 'something',
'type' => 'name',
),
1 => array(
'language' => 'fi',
'value' => 'jotain',
'type' => 'name',
),
2 => array(
'language' => 'sv',
'value' => 'någonting',
'type' => 'name',
),
);
function myfunction(array $serviceNames, $field)
{
foreach($serviceNames as $service)
{
if ( $service['language'] === $field )
return $service['value'];
}
return false;
}
echo myfunction($serviceNames, 'en');
Output will : something
you would have to go through each elements of the array, using the foreach statement.
something like:
function getValueForLang($lang, array $arr)
{
foreach ($arr as $desc) {
if ($desc['language'] == $lang) {
return $arr['value'];
}
}
return null;
}
getValueForLang('en', $serviceNames); // gets your value, null if not found
see also:
https://secure.php.net/manual/en/control-structures.foreach.php
So I have a function called vendorGet() and it contains an array of vendor names and their logos. I call the vendorGet() function in another array and pass it a string argument to tell it which vendor to output from the array of vendors. Does doing this cause the PHP script to create this array every time the function is called, or does it create it once within the function and reference itself each time?
Hope that made sense. Let me know if there is anything I can clarify.
Here is some (shortened down and simplified) code as a reference,
// Vendor Fetcher
function vendorGet($data)
{
$vendor = array(
'foo' => array(
'name' => 'Foo Products',
'image' => (VENDOR_IMG . 'foo/foo-logo.png'),
),
'bar' => array( // ABT
'name' => 'Bar Inc.',
'image' => (VENDOR_IMG . 'bar/bar-logo.png'),
),
);
return $vendor[$data];
}
// Array calling vendorGet() function
$catalogue = array(
'chapter-1' => array(
'vendors' => array(
1 => vendorGet('foo'),
2 => vendorGet('bar'),
),
),
);
The code you have written will re-create the array every single time the function is called.
You can create the array outside of this function and still have the function reference the array if it's within a class using "this" or you can pass in the array as a variable to the function.
In short, the array will be set up every time the function is called because you're defining it within the function
If you want to avoid this you can use a class
class vendor {
public static $vendor = array(
'foo' => array(
'name' => 'Foo Products',
'image' => (VENDOR_IMG . 'foo/foo-logo.png'),
),
'bar' => array( // ABT
'name' => 'Bar Inc.',
'image' => (VENDOR_IMG . 'bar/bar-logo.png'),
),
);
public static function get($data) {
return self::$vendor[$data];
}
}
You don't need a function to do this. Arrays allow you to access by key.
// Vendor Array
$vendor = array(
'foo' => array(
'name' => 'Foo Products',
'image' => (VENDOR_IMG . 'foo/foo-logo.png'),
),
'bar' => array( // ABT
'name' => 'Bar Inc.',
'image' => (VENDOR_IMG . 'bar/bar-logo.png'),
),
);
// Array getting vendor by key
$catalogue = array(
'chapter-1' => array(
'vendors' => array(
1 => $vendor['foo'],
2 => $vendor['bar'],
),
),
);
Arrays allow you to access a key and return its corresponding value. You can also can also pull deeper into that array like this:
echo $vendor['foo']['name'];
This will output:
Foo Products
To clarify:
PHP has exactly two scopes: "local" and "global." Any variable declared outside of a function is "global." Any variable declared within a function is "local," unless the global directive is used to say that it is, in fact, global.
PHP fully supports recursion: a function may (directly or indirectly) call itself. The local variables of each active instance of that function are private to that instance.
Variables are normally passed into functions "by value," which means that a duplicate is made.
If you have many related functions that need to share common data, consider making a class, with the functions being "methods" of that class. Now, they all have access to $this, which refers to the object-instance to which they belong. Notice also that properties (and methods) can be declared either public or private, which is an effective way to keep other parts of the code from seeing (and therefore, possibly meddling with ...) them.
Yes it creates the array each time you call the function.
Performing a memory usage asserts it.
<?php
function vendorGetArray()
{
return array(
'foo' => array(
'name' => 'Foo Products',
'image' => ( 'foo/foo-logo.png'),
),
'bar' => array( // ABT
'name' => 'Bar Inc.',
'image' => ( 'bar/bar-logo.png'),
),
);
}
function memoryUsage()
{
echo "memory: ".(memory_get_peak_usage(false)/1024/1024)." MiB<br>";
}
$vendorArray = vendorGetArray();
// Array calling vendorGet() function
$catalogue = array(
'chapter-1' => array(
'vendors' => array(
1 => $vendorArray['foo'],
2 => $vendorArray['bar']
),
),
);
memoryUsage();
?>
The above code prints:
memory: 0.231658935547 MiB
While your code
<?php
function vendorGet($data)
{
$vendor = array(
'foo' => array(
'name' => 'Foo Products',
'image' => ( 'foo/foo-logo.png'),
),
'bar' => array( // ABT
'name' => 'Bar Inc.',
'image' => ( 'bar/bar-logo.png'),
),
);
return $vendor[$data];
}
function memoryUsage()
{
echo "memory: ".(memory_get_peak_usage(false)/1024/1024)." MiB<br>";
}
// Array calling vendorGet() function
$catalogue = array(
'chapter-1' => array(
'vendors' => array(
1 => vendorGet('foo'),
2 => vendorGet('bar'),
),
),
);
memoryUsage();
would print:
memory: 0.231948852539 MiB
I want to add both an ID and NAME for my drop down (so that I could get the value using jQuery.
but it seems that CI won't allow. Is there another way?
$device = array(
'name' => 'device',
'id' => 'device'
);
$device_opts = array(
'monitor' => 'Chair',
'keyboard' => 'Keyboard',
'mouse' => 'Mouse',
'table' => 'table',
'UPS' => 'UPS',
);
echo form_dropdown($device, $device_opts);
try this
echo form_dropdown("device", $device_opts,"","id='device'");
Try like
$device = array(
'id' => 'device'
);
form_dropdown('device', $device_opts, '', $device);
You need to give name as first option for the DropDown and the remaining will come under extra options for that DropDown
I have the following two things:
$_POST array with posted data
$params array with a path for each param in the desired data array.
$_POST = array(
'name' => 'Marcus',
'published' => 'Today',
'url' => 'http:://example.com',
'layout' => 'Some info...',
);
$params = array(
'name' => 'Invoice.name',
'published' => 'Page.published',
'url' => 'Page.Data.url',
'layout' => 'Page.Data.layout',
);
I would like to generate the $data array like the example below.
How can I do that?
Notice how the "paths" from the $params array are used to build the keys for the data array, filling it with the data from the $_POST array.
$data = array(
'User' => array(
'name' => 'Marcus',
),
'Page' => array(
'published' => 'Today',
'Data' => array(
'url' => 'http:://example.com',
'layout' => 'Some info...',
),
),
);
I would use referenced variables:
$post = array( // I renamed it
'name' => 'Marcus',
'published' => 'Today',
'url' => 'http:://example.com',
'layout' => 'Some info...',
);
$params = array(
'name' => 'Invoice.name',
'published' => 'Page.published',
'url' => 'Page.Data.url',
'layout' => 'Page.Data.layout',
);
echo '<pre>'; // just for var_dump()
foreach($post as $key=>$var){ // take each $_POST variable
$param=$params[$key]; // take the scheme fields
$path=explode('.',$param); // take scheme fields as an array
$temp=array(); // temporary array to manipulate
$temp_original=&$temp; // we need this the same as we're going to "forget" temp
foreach($path as $pathvar){ // take each scheme fields
$temp=&$temp[$pathvar]; // go deeper
}
$temp=$var; // that was the last one, insert it
var_dump($temp_original); // analize carefully the output
}
All you have to do now is to combine them all, they are not exactly what you want, but this will be easy.
And please note, that each $temp_original fields are pointing at $post variable data! (&string instead of string). You may want to clone it somehow.