Useful php functions
The last notes
All English-language materials have been translated fully automatically using the Google service
I've been collecting this hodgepodge for a long time and I haven't found most of the authors / don't remember. If you find out your code, then write - I will add your authorship
Search for key matches in a multidimensional array
function search ($ array, $ key, $ value)
{
$ results = array ();
if (is_array ($ array)) {
if (isset ($ array [$ key]) && $ array [$ key] == $ value) {
$ results [] = $ array;
}
foreach ($ array as $ subarray) {
$ results = array_merge ($ results, search ($ subarray, $ key, $ value));
}
}
return $ results;
}
$ arr = array (0 => array (id => 1, name => "cat 1"),
1 => array (id => 2, name => "cat 2"),
2 => array (id => 3, name => "cat 1"));
print_r (search ($ arr, 'name', 'cat 1'));
Convert StdClassObject to Array
$ array = json_decode (object, True);
Split array by index
// an array
$ array = array (1, 2, 3, "products", 4, 5);
// $ offset = 3
$ offset = array_search ("products", $ array);
// array (4,5)
$ last_batch = array_slice ($ array, ($ offset + 1));
// array (1,2,3)
$ first_batch = array_slice ($ array, 0, $ offset);
Remove the last element of the array
array_pop($stack)
Determine the last index of the array
$ array = array (
'first' => 123,
'second' => 456,
'last' => 789,
);
end ($ array); // move the internal pointer to the end of the array
$ key = key ($ array); // fetches the key of the element pointed to by the internal pointer
var_dump ($ key);
What to do if json_encode
doesn't work
function safe_json_encode ($ value, $ options = 0, $ depth = 512) {
$ encoded = json_encode ($ value, $ options, $ depth);
switch (json_last_error ()) {
case JSON_ERROR_NONE:
return $ encoded;
case JSON_ERROR_DEPTH:
return 'Maximum stack depth exceeded'; // or trigger_error () or throw new Exception ()
case JSON_ERROR_STATE_MISMATCH:
return 'Underflow or the modes mismatch'; // or trigger_error () or throw new Exception ()
case JSON_ERROR_CTRL_CHAR:
return 'Unexpected control character found';
case JSON_ERROR_SYNTAX:
return 'Syntax error, malformed JSON'; // or trigger_error () or throw new Exception ()
case JSON_ERROR_UTF8:
$ clean = utf8ize ($ value);
return safe_json_encode ($ clean, $ options, $ depth);
default:
return 'Unknown error'; // or trigger_error () or throw new Exception ()
}
}
function utf8ize ($ mixed) {
if (is_array ($ mixed)) {
foreach ($ mixed as $ key => $ value) {
$ mixed [$ key] = utf8ize ($ value);
}
} else if (is_string ($ mixed)) {
return utf8_encode ($ mixed);
}
return $ mixed;
}
Thanks to Konstantin for the function from the site How to solve JSON_ERROR_UTF8 error in php json_decode?
Comments