I use CakePHP framework. I have an array which corresponds a model's records. I have to handle it in the way, that all the integers and floats are output as integers and floats just like in java without quotes(111 or 11.1 instead of this '111.1' or '11.1'). I found the way to return all the values in this way: return json_encode($data, JSON_NUMERIC_CHECK);. The question is: is there any way to exclude some numeric fields to be outpt in this way? In other words: I have two numeric fields: field1 and field2, and they have to be with quotes. Meantime all other numeric fields must be without quotes. How could I implement this ?
My array looks so:
array(
(int) 0 => array(
'password' => '*****',
'id' => '2',
'number' => '2',
'debtor_number' => null,
'name' => 'Ziegler',
'firstname' => 'Lisa',
'address' => 'Frau',
'title' => '',
'name_extension' => '',
'company' => '',
'company_function' => '',
'street' => 'Feldbergstr. 13-15',
'street2' => null,
'postbox' => '',
'street_or_postbox' => '1',
'zip' => '60318',
'city' => 'Frankfurt am Main',
),
(int) 1 => array(
'password' => '*****',
'id' => '3',
'number' => '3',
'debtor_number' => null,
'name' => 'Trappatoni',
'firstname' => 'Günther',
'address' => 'Herr',
'title' => '',
'name_extension' => '',
'company' => '',
'company_function' => '',
'street' => 'Trilluper Weg 17',
'street2' => null,
'postbox' => '',
'street_or_postbox' => '1',
'zip' => '60594',
'city' => 'Frankfurt am Main',
First of all, a little example of how JSON_NUMERIC_CHECK works:
$data = [112, '34', 5.6, '7.8'];
echo json_encode($data) . PHP_EOL;
echo json_encode($data, JSON_NUMERIC_CHECK) . PHP_EOL;
... prints:
[112,"34",5.6,"7.8"]
[112,34,5.6,7.8]
There isn't any feature to determine which values should be parsed (and if they wanted to add it, what would its syntax be?). The only way to get the results you want is to ensure that source data is already using the appropriate PHP data types. And that's something you can certainly do (though the exact details depend on your specs):
$person = [
'age' => 33,
'zip_code' => '09007',
];
$person['age'] = is_null($person['age']) ? null : (int)$person['age'];
echo json_encode($person);
... prints:
{"age":33,"zip_code":"09007"}
Another solution for this issue if it's important enough for you to solve it in a robust way, and that would be to use the JMS Serializer library.
You would need to define a class for your data, but after that, whatever types you have defined via annotation will be honored during serialization.
With that said, Alvaro's post shows that casting will work. So, something like this should also work:
// Fix all Numerics
$data = json_decode(json_encode($data, JSON_NUMERIC_CHECK), true);
// Fix your 2 strings
$callback = function($row) {
if (array_key_exists('field1', $row)) {
$row['field1'] = (string)$row['field1'];
}
if (array_key_exists('field2', $row)) {
$row['field2'] = (string)$row['field2'];
}
return $row;
}
$data = array_map($callback, $data);
// This should be ready for final encode
return json_encode($data);
I tried this and it worked fine for me because I would only check JSON_NUMERIC_CHECK on id and with this
echo json_encode($article, JSON_NUMERIC_CHECK)
,and I got id and telephone as int.
Try this
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$row['id'] = (int)$row['id'];
$row['telephone'] = (string)$row['telephone'];
$db_data[] = $row;
}
//format json
$article->status = true;
$article->message = "success";
$article->employee = $db_data;
//return json
echo json_encode($article);
} else {
}
Related
I have an odd question which I cannot find an answer to on Google or SO.
I have an array containing all the bits of information about the pages on my website. So the array contains multiple of the arrays like the example below:
'home' =>
array (size=7)
'title' => string '' (length=0)
'url' => string 'home.php' (length=8)
'mobile' => string 'home.php' (length=8)
'keywords' => string '' (length=0)
'description' => string 'test123' (length=126)
'login_needed' => boolean false
'original_page' => string 'home' (length=4)
What I need to do is to find each array that contains a value that comes from a search bar. For example if the user searches for "bruidsmode" every array that contains "bruidsmode" should be put into another array which I can then output into elements to display on the website.
Below you will find a stripped example of what I have on my page. (I tried making a working example but was unable to do so):
<?php
$config['menu']["home"] = array (
'title' => '',
'url' => 'home.php',
'mobile' => 'home.php',
'keywords' => '',
'description' => '',
'login_needed' => FALSE
);
$config['menu']["bruidsmode"] = array (
'title' => '',
'url' => 'bruidsmode.php',
// 'mobile' => 'bruidsmode.php',
// 'mobile' => 'bruidsmode.php',
'keywords' => '',
'description' => '',
'login_needed' => TRUE,
'robot' => FALSE
);
if(isset($_POST['generalsearch']) && isset($_POST['generalsearchresult'])){
// Put search value into variable
$searchvalue = $_POST['generalsearchresult'];
// Fill variable with all page items
$array = $config['menu'];
// Set search cretaria to search in array
$key = $searchvalue;
// Search for key value inside array
$result = #$array[$key] ?: null;
if($result == null){
echo "Geen resultaten gevonden...";
}else{
var_dump($result);
}
}
?>
<form method="POST">
<input type="text" name="generalsearchresult">
<input type="submit" name="generalsearch">
</form>
The above code works but only outputs arrays which exactly match the search criteria. So for example the searchterm "bruidsmode" with the above code outputs only the page "bruidsmode" but not the page "bruidsmode-overzicht" for example.
I hope the above is understandable, if not please tell me how to improve it.
Kind regards,
Robbert
Your code isn't really what I would call a search. In order to search you should loop over the array to find potential matches, rather than return the requested property.
function searchMenu($menu, $term) {
$matches = [];
foreach($menu as $key => $value) {
if (stripos($key, $term) !== false) {
$matches[] = $value;
}
}
return $matches;
}
if(isset($_POST['generalsearch']) && isset($_POST['generalsearchresult'])){
$result = searchMenu($config['menu'], $_POST['generalsearchresult']);
if(!count($result)){
echo "Geen resultaten gevonden...";
}else{
var_dump($result);
}
}
If you want to return multiple results, you will need to store them in an array and return that.
If you are going to do that, you can extend the search to check against child fields as well, not just the top level keys:
$page_data =[
'my-cat' => [
'title' => '',
'url' => 'my-cat.php',
'mobile' => 'my-cat.php',
'keywords' => 'cat,kitten',
'description' => 'i love my cat',
'login_needed' => false,
'original_page' => 'mycat',
],
'home' => [
'title' => '',
'url' => 'home.php',
'mobile' => 'home.php',
'keywords' => 'cat,dog,other',
'description' => 'a site about cats',
'login_needed' => false,
'original_page' => 'home',
],
'about' => [
'title' => '',
'url' => 'about.php',
'mobile' => 'about.php',
'keywords' => 'about',
'description' => 'about me',
'login_needed' => false,
'original_page' => 'about',
],
];
function search(array $page_data_to_search, string $search_term, array $fields_to_search): array{
$out=[];
$search_fields = array_flip($fields_to_search); //O(1)
foreach($page_data_to_search as $key => $page_data){
//first test the key
if(isset($search_fields['key']) && strpos($key, $search_term) !==false){
$out[$key]=$page_data;
continue; //no need to check other fields
}
//then the user supplied fields
foreach($search_fields as $field => $unused){
if(isset($page_data[$field]) && strpos($page_data[$field], $search_term) !==false){
$out[$key]=$page_data;
break;
}
}
}
return $out;
}
echo '<pre>';
var_dump(search($page_data, 'cat', ['key', 'keywords', 'description']));
I never used generators in PHP. I understand the way to use it :
Foreach an array to do some tasks for each value like greping a specific line into a big file to remove some caracteres..
What I need :
I need to retrieve all bands from my dabatase. Sure I have the 'limit' argument to don't exceed the PHP's memory (there're 30 000 bands..).
I have to filters values and return a new array to the client into my REST API.
What I want to know :
Is it interesting for me to create a method into a trait called 'generator' to perform the code bellow ?
In all cases, I have to create a new array to return it into my method
$bands = Models\Bands::find($bandsParameters);
$json = [];
foreach ($bands as $band) {
$followers = $band->getFollowers();
$followersArr = [];
foreach ($followers as $follower) {
$followerImage = $follower->getImage();
$followerObj = (object)[
'id' => $follower->id,
'username' => $follower->username,
'image' => $followerImage->url,
'online' => $follower->online,
'createdOn' => $follower->createdOn,
'updatedOn' => $follower->updatedOn,
'lastLogin' => $follower->lastLogin,
];
$followersArr[] = $followerObj;
}
$info = $band->getInfo($bandInfoParameters)->getFirst();
$bandObj = (object)[
'id' => $band->id,
'name' => $band->name,
'style' => $band->styles,
'country' => $band->country,
'summary' => isset($info->summary) ? $info->summary : null,
'followers' => $followersArr,
'createdOn' => $band->createdOn,
'updatedOn' => $band->updatedOn,
'authoredBy' => $band->authoredBy,
'updatedBy' => $band->updatedBy,
];
$json[] = $bandObj;
}
return ['key' => 'bands', 'value' => $json];
first of, just wanted to let you know that I am a newbie at CI. but I am having trouble with this piece of code where is breaking and I can't seem to be able to find the answer anywhere.
for some reason the code is breaking at the first if statement.. if possible could you help me out understand what is really happening there?
Thank you all for your help!
function main
{
$this->load->model(getData) psudo code for this area...
}
---model---
function getData....
{
Sql = this->db->query(sql code that returns all the information required.)
$result = $sql->result_array();
$types = array ( 'EVENT|TIME' => array( 'id' => 1, 'name' => 'Regular' ),
'PROPOSITION|REGULAR' => array( 'id' => 2, 'name' =>'Propositions'),
'EVENT|TIME' => array( 'id' => 3, 'name' => 'Now' ),
'PROPOSITION|FUTURES' => array( 'id' => 4, 'name' => 'Future' ));
$var = array();
foreach ($result as $event) {
$cat = $event['type'] . '|' . $event['sub_type'];
$typeId = $types[$cat]['id'];
if(!is_array($var[$event['event_id']]['var'][$event['type_id']]))
{
if(!is_array($var[$event['event_id']]))
{
$var[$event['event_id']] = array( 'event_name' =>
$event['event_name'],'event_abbreviation' =>
$event['event_abbreviation']);
}
$var[$event['event_id']]['var'][$event['type_id']] = array(
'type_name' => $event['abbreviation'],'type_abbreviation' => $event['name']
);
}
$event[$event['event_id']]['var'][$event['type_id']]['types'][$typeId] =
$types[$cat]['name'];
}
return $myResults;
}
In this line
if(!is_array($var[$event['event_id']]['var']$event['type_id']]))
You are missing a [ somewhere. I'm guessing before $event['type_id'].
So replace with:
if(!is_array($var[$event['event_id']]['var'][$event['type_id']]))
My initial array is
$employees = array(
array('name' => 'jack',
'area' => 'crafts'),
array('name' => 'janet',
'area' => 'aquatics'),
array('name' => 'brad',
'area' => 'crafts')
);
I am trying to create a new array based on the search results of another array so the new array should look like this if I search for 'crafts':
$employees2 = array(
array('name' => 'jack',
'area' => 'crafts'),
array('name' => 'brad',
'area' => 'crafts')
);
What is the simplest solution I can do get get this new result.
foreach($employees as $key => $value){
if($value['area']=='crafts'){
$employees2[] = $value;
}
}
This quite simply loops through the first array and checks the value of "area" in the internal array. If the value is equal to "crafts" you can then put that into a new array which is called $employees2. You can change crafts to whatever you want and add anything you want between the [ ] in employees2 if you wish to customise the key.
Try this:
$employees = array(
array('name' => 'jack',
'area' => 'crafts'),
array('name' => 'janet',
'area' => 'aquatics'),
array('name' => 'brad',
'area' => 'crafts')
);
$employees2 = array();
foreach ($employees as $key) {
if($key['name'] == "jack")
{
array_push($employees2,array('name'=>$key['name'],'area'=>$key['area']));
}
}
var_dump($employees2);
The array_push do all the trick ;)
Saludos.
You could simplify the syntax (but not the algorythmic complexity) by using a utility-belt library Underscore.php (http://brianhaveri.github.com/Underscore.php/)
There's a number of array-"plucking" methods that saves you the need to write loops, but under the bonnet it does much of the same as decribed in answers above.
I will assume that the possible result set can be large. In which case you would want to process the array with as little extra memory as possible. For this I suggest iterating through the array by reference and unsetting the items that do not match your criteria. Possibly less overhead than creating a new array to store the items that match your filter. Then you can check if the array is empty or not to determine if the filter returns any results. Like so:
<?php
// maybe this will be set through an option from the UI
$area_filter = 'crafts';
// fetched results
$employees = array(
array('name' => 'jack',
'area' => 'crafts'),
array('name' => 'janet',
'area' => 'aquatics'),
array('name' => 'brad',
'area' => 'crafts')
);
// filter out the items that match your filter
foreach($employees as $i => &$employee){
if($employee['area'] != $area_filter){
unset($employees[$i]);
}
}
// do something with the results
if(!empty($employees)){
print_r($employees);
} else {
echo "Sorry, your filter '$area_filter' did not match any results\n";
}
?>
Try this :
$employees = array(
array('name' => 'jack',
'area' => 'crafts'),
array('name' => 'janet',
'area' => 'aquatics'),
array('name' => 'brad',
'area' => 'crafts')
);
$employees = array_filter($employees, function($employee) {
return ($employee['area'] == 'crafts' );
});
echo "<pre>";
print_r($employees);
I'm writing a 'get' function in a model class in codeigniter, but I need to process some of the data as it's returned, ideally without a whole bunch of overhead.
function get_answers($p)
{
$result = $this->db->get_where('answer', array('a_upid_fk' => $p))->result();
// foreach ($result->answer as $ans) {
// $result->answers = explode( '|', $ans, -1 );
// }
return $result;
}
The results look like this:
array (
0 =>
stdClass::__set_state(array(
'aid' => '742',
'a_upid_fk' => '231',
'answer' => '4555|||',
'a_qid_fk' => '70',
'created' => '2012-04-20 15:35:38',
'last_modified' => '2012-04-20 15:36:11',
'revision' => '1',
)),
1 =>
stdClass::__set_state(array(
'aid' => '743',
'a_upid_fk' => '231',
'answer' => NULL,
'a_qid_fk' => '71',
'created' => '2012-04-20 15:35:38',
'last_modified' => '2012-04-20 15:35:38',
'revision' => '1',
)) ...
the problem is the answer is stored as a pipe delimited list of answers, but I want the function to return it as an exploded array instead. I'm not sure of the syntax and how to create and replace or append the array to the array of objects I've pasted above.
You can see some code I've been trying commented out.
Ideally instead of 'answer' => '4555|||',
I would like to have
'answer' => array (
0 => '4555',
1=> '',
2=> '')
I have no problem making the array using explode but I'm not sure how to modify the original codeigniter active-record result.
Loop thru your sub-arrays:
$answer_array = explode('|', $answer);
foreach ($aswer_array as $instance)
{
$result[] = $instance;
}
Define __set_state()), call it using - $subarray = $result[0][$object->answer].