I have a array, which I need to check if it's associative or not.
The array can look like this:
[preview] => Array
(
[0] => Array
(
[type] => web
[side] => left
)
[1] => Array
(
[type] => web
[side] => right
)
)
And that is perfect. But sometimes, I get this:
[preview_file] => Array
(
[type] => artwork
[side] => right
)
In this case, I need to add a index of 0 to make the array look like this:
[preview_file] => Array
(
[0] => Array
(
[type] => artwork
[side] => right
)
)
I'm using this function to check if it's assoctiative:
function is_assoc($array) {
return (bool)count(array_filter(array_keys($array), 'is_string'));
}
If not, I need to somehow add the [0]. Doe=s anyone have an idea?
I would check the values instead of the keys. It also sounds like you can get away just checking the first value:
function is_assoc($array) {
return is_array(reset($array));
}
Was your question about how to make the actual change? This ought to work:
if (!is_assoc($preview)) {
$preview = array($preview);
}
Different way:
if(!isset($array[0])) {
$array[0] = $array;
}
Related
I have a function in PHP (using Symfony) where I am building an array by passing a value into the array first, and then I am looping through every record but changing the key/value each time until I run out of values...
For example:
I pass this value into my getFieldKeys() function listed below:
array(
'fieldKey'=>'123'
);
Inside of this function, I first add this value to the fieldKey array and then see if there are any records that match my query...
If there are records then loop through each of those records and send the fieldKey the value back to the same function and add the value to the array...
This all works but my array look aweful. Need help cleaning up this code, not sure what to do...
public function getFieldKeys($array){
$em = $this->getEntityManager();
$fieldKeys[] = $array['fieldKey']; // add original value to fieldKey array...
// loop over any results and and pass key back into this same function and then do a look up on that key and repeat the process until finished...
$keys = $em->getRepository('AppBundle:FieldKeys')->findBy([
'fieldKey' => $array['fieldKey'],
]);
foreach($keys as $key) {
$fieldKeys[] = $this->getFieldKeys([
'fieldKey'=>$key->getFieldKey(),
]);
}
return $fieldKeys;
}
My final array looks like this - yikes!
Array
(
[0] => ccrs_date
[1] => Array
(
[0] => prelim_title_report_date
[1] => Array
(
[0] => additional_escrow_deposit_date
[1] => Array
(
[0] => earnest_money_date
[1] => Array
(
[0] => acceptance_date
[1] => Array
(
[0] => contract_date
[1] => Array
(
[0] =>
)
)
)
)
)
)
)
What I am hoping for is something more like this...
Array
(
[0] => ccrs_date
[1] => prelim_title_report_date
[2] => additional_escrow_deposit_date
[3] => earnest_money_date
[4] => acceptance_date
[5] => contract_date
[6] => prelim_title_report_date
)
Thanks!
You have written a recursive function to achieve your keys array - good idea. However your function returns an array and you are adding the resulting array recursivley to the current array which causes an array nesting one down per level.
This might be what you need as your second key is always an array but you are just looking for the key:
public function getFieldKeys($array){
$em = $this->getEntityManager();
$fieldKeys[] = $array['fieldKey']; // add original value to fieldKey array...
// loop over any results and and pass key back into this same function and then do a look up on that key and repeat the process until finished...
$keys = $em->getRepository('AppBundle:FieldKeys')->findBy([
'fieldKey' => $array['fieldKey'],
]);
foreach($keys as $key) {
$tmp = $this->getFieldKeys([
'fieldKey'=>$key->getFieldKey(),
]);
$fieldKeys[] = reset($tmp);
}
return $fieldKeys;
}
I want to get the key of the array where, for example, "type" equals "UniqueType1" (in this case 0) in PHP.
The complete array is huge and from an API, so i can't modify the raw data.
The description of my problem is pretty bad but I've never done something similar. Sorry for that.
Array
(
[summary] => Array
(
[0] => Array
(
[type] => UniqueType1
[aggregated] => Array
(
....
)
[modifydate] => 1389890963000
)
[1] => Array
(
[type] => UniqueType2
[aggregated] => Array
(
....
)
[modifydate] => 1389890963000
)
) )
Unless I'm missing something, this looks like a case of simply iterating through an array and checking the value of a specific key in a sub-array.
Assuming that $array is your outer array...
foreach($array["summary"] as $index => $row)
{
if($row["type"] == "UniqueType1")
{
$targetIndex = $index;
break;
}
}
echo "The target index is " . (isset($targetIndex) ? $targetIndex : "not found.");
Let's say i have this function that seeks for a value inside a bidimensional array:
function findValueBi($array, $field, $value, $returnfield)
{
foreach($array as $key => $product)
{
if ( $product[$field] === $value )
return $product[$returnfield];
}
return false;
}
And the bidimensional array looks like this:
Array
(
[0] => Array
(
[number] => 2
[type] => unimodal
)
[1] => Array
(
[number] => 6
[type] => unimodal
)
[2] => Array
(
[number] => 8
[type] => multimodal
)
[3] => Array
(
[number] => 27
[type] => multimodal
)
[4] => Array
(
[number] => 29
[type] => multimodal
)
)
What the function does, is to look for a given value inside the 'number' key. If it's found, i retrieve its corresponding 'type' key value. For example, if i am looking for the 'number' 29, then i will get the 'type' value "multimodal" (the last item of the array sample). Otherwise, if the value is not found, the function returns false.
So, the way i retrieve this value is as follows:
if(findValueBi($numbers_patterns,'number',$number,'type')!==false){
$resultado=findValueBi($numbers_patterns,'number',$number,'type');
return $resultado;
}
else{ ... }
Is there a better and/or faster way to do this? Is it possible to retrieve the info right inside the if statement? As you can see, I am calling the function twice, so how can i call it once with the if statement???
You could just elect to use it the first time, then use it inside the if:
$resultado = findValueBi($numbers_patterns,'number',$number,'type'); // call it once
if($resultado !== false){
// use $resultado here
}
I have a multi-dimensional array (There is more than one item in "data" but i'm just showing one for this question):
Array
(
[data] => Array
(
[0] => Array
(
[to] => Array
(
[data] => Array
(
[0] => Array
(
[name] => fake name
[id] => 668071477234
)
[1] => Array
(
[name] => fake name
[id] => 1345556711
)
)
)
[updated_time] => 2012-12-24T23:46:26+0000
[id] => 327424994013537
)
)
)
I am trying to loop thru the array and determine if the id matches a variable sent from $_REQUEST, and if it does, I only want to return the "updated_time" value of the iteration.
Here's what I have but the date is always wrong, and doesn't match the proper iteration:
foreach($userOutbox['data'] as $outbox){
foreach($outbox['to']['data'] as $user){
if($user['id'] == $_REQUEST['facebook_id']){
$last_message_date = $outbox['updated_time'];
}
}
}
It's late and my eyes and brain are not helping me. Can anyone give me any direction?
Here's the solution that worked for me, just added break 2; Thanks for your help:
foreach($userOutbox['data'] as $outbox){
foreach($outbox['to']['data'] as $user){
if($user['id'] == $_REQUEST['facebook_id']){
$last_message_date = $outbox['updated_time'];
break 2;
}
}
}
I'm looking for a way to make it so cake returns all database data in the same format/structure... Currently it returns two different types of format depending on the relationship.
If a model 'B' is associated with the current model 'A' being queried it will then place model associations for 'B' underneath it as you can see in [User] below. I want it so that all queries use that structure.
example:
$this->find('all', ....
returns:
Array
(
[0] => Array
(
[UserGroup] => Array
(
[id] => 53
[user_id] => 100003332014851
[media_id] =>
[name] => john
[description] => qwasdfad
)
[User] => Array
(
[id] => 100003332014851
[session_id] => ssm2qbrotmm13ho1ipm8ii2492
[username] =>
[password] => -1
[Planner] => Array
(
)
[Purchase] => Array
(
)
[Listing] => Array
(
)
)
)
I want this to look like:
Array
(
[0] => Array
(
[UserGroup] => Array
(
[id] => 53
[user_id] => 100003332014851
[media_id] =>
[name] => john
[description] => qwasdfad
[User] => Array
(
[id] => 100003332014851
[session_id] => ssm2qbrotmm13ho1ipm8ii2492
[username] =>
[password] => -1
[Planner] => Array
(
)
[Purchase] => Array
(
)
[Listing] => Array
(
)
)
)
)
)
In CakePHP, the find() method return data like your first format. But If you want to format like second one then you have to process it by hand (try to avoid this if possible)
$data = $this->find('all');
$assocs = Set::extract('/User', $data); // extracting all `User` array
foreach($assocs as $key => $assoc) {
unset($data[$key]['User']); // removing the associate `User` from `$data`
$data[$key]['UserGroup']['User'] = $assoc['User']; // adding associate under `UserGroup`
}
ended up doing this... it changes the output to what we need. The top level item does not have a header which is fine I just adjusted our scripts for that... maybe this will help somebody else if they need a custom idea
also no guarantee this covers all possible results but so far it works with all the queries we have.
class AppModel extends Model {
function afterFind($results, $primary) {
//if this is a primary, structure like a secondary so entire site is same format
if ($primary) {
$class = get_class($this);
//simple fix for primary
foreach ($results as $key => $result) {
$result = $this->formatData($result, $class);
$results[$key] = $result;
}
}
return $results;
}
function formatData($result, $class) {
$array = array();
if (isset($result[$class])) {
$array = $result[$class];
unset($result[$class]);
}
$array += $result;
return $array;
}
You can also use contain in this case along with find as UserGroup.User for your desired result