In short, I need a way to change:
Array
(
[CrmOrder] => Array
(
[crm_schedule_id] => 59
)
)
...into this (using PHP)....
Array
(
[CrmOrder] => Array
(
[0] => Array
(
[crm_schedule_id] => 59
)
)
)
The reason I need to do this is because I want to use the CakePHP saveAll() function with an array that I'm getting from the Wizard Component. Cake's saveAll needs the data to be one level deeper because CrmOrder belongsTo CrmPerson which hasMany CrmOrder.
As this isn't necessarily a Cake specific question, I'm also adding the 'php' tag to this question.
You should be able to leverage the FormHelper to produce the intended output like so:
echo $this->Form->input('CrmOrder.0.crm_schedule_id');
(Note the 0 in dot-notation. See second code block on this page in the manual.)
$input = array( /* your data */ );
$output = $input;
$output['CrmOrder'] = array($output['CrmOrder']);
$newArray = array();
foreach( $oldArray as $key => $value ) {
$newArray[ $key ] = array( $value );
}
Demo:
$data = array(
'CrmOrder' => array(
'crm_schedule_id' => 59,
),
);
$data = array_map(function($v){return array($v);}, $data);
var_dump($data);
Related
I would like to build a multidimensional array from an array. For example I would like
$test = array (
0 => 'Tree',
1 => 'Trunk',
2 => 'Branch',
3 => 'Limb',
4 => 'Apple',
5 => 'Seed'
);
to become
$test =
array (
'Tree' => array (
'Trunk' => array (
'Branch' => array (
'Limb' => array (
'Apple' => array (
'Seed' => array ()
)
)
)
)
)
);
or more simply
$result[Tree][Trunk][Branch][Limb][Apple][Seed] = null;
I'm trying to do this with a recursive function but i'm hitting memory limit so I'm clearly doing it wrong.
<?php
$test = array (
0 => 'Tree',
1 => 'Trunk',
2 => 'Branch',
3 => 'Limb',
4 => 'Apple',
5 => 'Seed'
);
print_r($test);
print "results of function";
print_r(buildArray($test));
function buildArray (&$array, &$build = null)
{
if (count($array) > 0)
{
//create an array, pass the array to itself removing the first value
$temp = array_values($array);
unset ($temp[0]);
$build[$array[0]] = $temp;
buildArray($build,$temp);
return $build;
}
return $build;
}
Here's an approach with foreach and without recursion, which works:
function buildArray($array)
{
$new = array();
$current = &$new;
foreach($array as $key => $value)
{
$current[$value] = array();
$current = &$current[$value];
}
return $new;
}
[ Demo ]
Now your function... first, using $build[$array[0]] without defining it as an array first produces an E_NOTICE.
Second, your function is going into infinite recursion because you are not actually modifying $array ($temp isn't the same), so count($array) > 0 will be true for all of eternity.
And even if you were modifying $array, you couldn't use $array[0] anymore, because you unset that, and the indices don't just slide up. You would need array_shift for that.
After that, you pass $build and $temp to your function, which results in further because you now you assign $build to $temp, therefore creating another loop in your already-infinitely-recurring loop.
I was trying to fix all of the above in your code, but eventually realized that my code was now pretty much exactly the one from Pevara's answer, just with different variable names, so... that's that.
This function works recursively and does the trick:
function buildArray($from, $to = []) {
if (empty($from)) { return null; }
$to[array_shift($from)] = buildArray($from, $to);
return $to;
}
In your code I would expect you see an error. You are talking to $build in your first iteration as if it where an array, while you have defaulted it to null.
It seems to be easy
$res = array();
$i = count($test);
while ($i)
$res = array($test[--$i] => $res);
var_export($res);
return
array ( 'Tree' => array ( 'Trunk' => array ( 'Branch' => array ( 'Limb' => array ( 'Apple' => array ( 'Seed' => array ( ), ), ), ), ), ), )
Using a pointer, keep re-pointing it deeper. Your two output examples gave array() and null for the deepest value; this gives array() but if you want null, replace $p[$value] = array(); with $p[$value] = $test ? array() : null;
$test = array(
'Tree',
'Trunk',
'Branch',
'Limb',
'Apple',
'Seed'
);
$output = array();
$p = &$output;
while ($test) {
$value = array_shift($test);
$p[$value] = array();
$p = &$p[$value];
}
print_r($output);
I am trying to delete an array whereby one of its values..(time) meet a specific condition. \The code I'm currently working with looks like this:
foreach($_SESSION as $key) {
foreach($key['time'] as $keys=>$value){
if(condition){
unset($key);
}
}
}
The array looks like this.
Array
(
[form1] => Array
(
[hash] => lFfKBKiCTG6vOQDa8c7n
[time] => 1401067044
)
[form5] => Array
(
[hash] => TTmLVODDEkI1NrRnAbfB
[time] => 1401063352
)
[form4] => Array
(
[hash] => XCVOvrGbhuqAZehBmwoD
[time] => 1401063352
)
I tried to adapt solutions from these pages but didn't work.
Remove element in multidimensional array and save
PHP - unset in a multidimensional array
PHP How to Unset Member of Multidimensional Array?
If you want to unset the values inside it, a simple single foreach will suffice. Consider this example:
$values = array(
'form1' => array('hash' => 'lFfKBKiCTG6vOQDa8c7n', 'time' => 1401067044),
'form5' => array('hash' => 'TTmLVODDEkI1NrRnAbfB', 'time' => 1401063352),
'form4' => array('hash' => 'XCVOvrGbhuqAZehBmwoD', 'time' => 1401063352),
);
$needle = 1401067044;
foreach($values as $key => &$value) {
if($value['time'] == $needle) {
// if you want to remove this key pair use this
unset($values[$key]['time']);
// if you just want to remove the value inside it
$value['time'] = null;
// if you want to remove all of this entirely
unset($values[$key]);
}
}
Fiddle
Unsetting in a for loop can lead to issues, its easier and better to use array_filter which is optimized for this kind of problem. Here is how to do it with your example. ideone running code
<?php
$ar = Array(
"form1" => Array
(
"hash" => 'lFfKBKiCTG6vOQDa8c7n',
"time" => '1401067044'
),
"form5" => Array
(
"hash" => 'TTmLVODDEkI1NrRnAbfB',
"time" => '1401063352'
),
"form4" => Array
(
"hash" => 'XCVOvrGbhuqAZehBmwoD',
"time" => '1401063352'
)
);
$condition = '1401067044';
$newArray = array_filter($ar, function($form) use ($condition) {
if (!isset($form['time'])) {
return true;
}
return $form['time'] != $condition;
});
var_export($newArray);
array_filter
Assuming your values are stored in $_SESSION
foreach($_SESSION as $key => $value) {
if(isset($value['time']) && $value['time'] < 1401063352) {
unset($_SESSION[$key]);
}
}
If you are storing your values in $_SESSION you may want to consider storing them in a subfield like $_SESSION['myForms'] so if you need to add other values to your session you can easily access only the values you need.
You need to do
unset($_SESSION[$key])
However as mentioned by Victory, array_filter is probably a better approach to this.
I'm working with dynamic data, so I'm trying to put that data into a bidimensional array.
I need a structure like this:
$array['something1'] = array ( 'hi1' => 'there1' , 'hi2' => 'there2' );
All this data is dynamically generated by a foreach, ex.:
$list = array ( 0 => 'something;hi1;there1' , 1 => 'something;hi2;there2' );
foreach ( $list as $key => $data )
{
// extract data
$columns = explode ( ';' , $data );
// set data
$items[$columns[0]] = array ( $columns[1] => $columns[2] );
}
How Can I do the previously described?
Right now the script is stepping over the previous key getting something like this:
$array['something1'] = array ( 'hi2' => 'there2' );
I hope you can help me.
Thanks.
The problem is that you are overwriting the value for the key when it already exists. You should modify to something like:
foreach ( $list as $key => $data )
{
// extract data
$columns = explode ( ';' , $data );
$outer_array_key = $columns[0];
$key = $columns[1];
$value = $columns[2];
// set data
$items[$outer_array_key][$key] = $value;
}
Here is how it can be done:
$list = array ( 0 => 'something;hi1;there1' , 1 => 'something;hi2;there2' );
$newlist =array();
foreach($list as $k=>$v){
$items = explode(';',$v);
$newlist[$items[0]][$items[1]]=$items[2];
}
echo "<pre>";
print_r($newlist);
echo "</pre>";
//output
/*
Array
(
[something] => Array
(
[hi1] => there1
[hi2] => there2
)
)*/
?>
Change your set data with something like this :
if(!array_key_exists($columns[0], $items))
$items[$columns[0]] = array();
$items[$columns[0]][$columns[1]] = $columns[2];
Is there a better way of doing this PHP code? What I'm doing is looping through the array and replacing the "title" field if it's blank.
if($result)
{
$count = 0;
foreach($result as $result_row)
{
if( !$result_row["title"] )
{
$result[$count]["title"] = "untitled";
}
$count++;
}
}
Where $result is an array with data like this:
Array
(
[0] => Array
(
[title] => sdsdsdsd
[body] => ssdsd
)
[1] => Array
(
[title] => sdssdsfds
[body] => sdsdsd
)
)
I'm not an experienced PHP developer, but I guess that the way I've proposed above isn't the most efficient?
Thanks
if($result) {
foreach($result as $index=>$result_row) {
if( !$result_row["title"] ) {
$result[$index]["title"] = "untitled";
}
}
}
You don't need to count it. It's efficient.
if ($result)
{
foreach($result as &$result_row)
{
if(!$result_row['title'])
{
$result_row['title'] = 'untitled';
}
}
}
Also, you may want to use something other than a boolean cast to check the existence of a title in case some young punk director releases a movie called 0.
You could do something like if (trim($result_row['title']) == '')
Mixing in a little more to #Luke's answer...
if($result) {
foreach($result as &$result_row) { // <--- Add & here
if($result_row['title'] == '') {
$result_row['title'] = 'untitled';
}
}
}
The key is the & before $result_row in the foreach statement. This make it a foreach by reference. Without that, the value of $result_row is a copy, not the original. Your loop will finish and do all the processing but it won't be kept.
The only way to get more efficient is to look at where the data comes from. If you're retrieving it from a database, could you potentially save each record with an "untitled" value as the default so you don't need to go back and put in the value later?
Another alternative could be json_encode + str_replace() and then json_decode():
$data = array
(
0 => array
(
'title' => '',
'body' => 'empty',
),
1 => array
(
'title' => 'set',
'body' => 'not-empty',
),
);
$data = json_encode($data); // [{"title":"","body":"empty"},{"title":"set","body":"not-empty"}]
$data = json_decode(str_replace('"title":""', '"title":"untitled"', $data), true);
As a one-liner:
$data = json_decode(str_replace('"title":""', '"title":"untitled"', json_encode($data)), true);
Output:
Array
(
[0] => Array
(
[title] => untitled
[body] => empty
)
[1] => Array
(
[title] => set
[body] => not-empty
)
)
I'm not sure if this is more efficient (I doubt it, but you can benchmark it), but at least it's a different way of doing the same and should work fine - you have to care about multi-dimensional arrays if you use the title index elsewhere thought.
Perhaps array_walk_recursive:
<?php
$myArr = array (array("title" => "sdsdsdsd", "body" => "ssdsd"),
array("title" => "", "body" => "sdsdsd") );
array_walk_recursive($myArr, "convertTitle");
var_dump($myArr);
function convertTitle(&$item, $key) {
if ($key=='title' && empty($item)) {$item = "untitled";}
}
?>
If you want sweet and short, try this one
$result = array(
array(
'title' => 'foo',
'body' => 'bar'
),
array(
'body' => 'baz'
),
array(
'body' => 'qux'
),
);
foreach($result as &$entry) if (empty($entry['title'])) {
$entry['title'] = 'no val';
}
var_dump($records);
the empty() will do the job, see the doc http://www.php.net/manual/en/function.empty.php
The following array is output from my db.
$this->db->select('code')->from('table');
$array = $this->db->get()->result_array();
//Output:
Array ( [0] => Array ( [code] => ASDF123 ) [1] => Array ( [code] => ASDF124 ) )
How can I find if a variable is contained in this array?
ie.
if(this_is_in_array($value, $array) == TRUE)...
What's the simplest way to to that with PHP?
I sincerely apologize for not wording this correctly the first time.
In case you wish to find the KEY of an array you would refer to the array_key_exists() method.
An example of this would be:
$array = array(
'key1' => 'value1',
'key2' => 'value2'
);
if ( array_key_exists( 'key2', $array ) )
return TRUE;
If you would however prefer to find the VALUE of an array, you would refer to the in_array() method. An example of this would be:
$array = array(
'key1' => 'value1',
'key2' => 'value2'
);
if ( in_array( 'value1', $array ) )
return TRUE;
Kevin:
foreach( $array as $key => $values )
{
if ( $values['code'] == 'ASD1234' )
{
// do something
}
}
make your array this:
$your_array = array('key1'=>'value1', 'key2'=>'value2');
then use this to see if the key exists in the array.
if (array_key_exists('key2', $your_array)) {
Unsure about what exactly you mean in your question, however, to answer your question title, you can use the array_key_exists() function to check if a given key or index exists within an array.
put your validation into the function
$input = 'ASDF123';
function check_input($input) {
$array = array(
0 => array('code' => 'ASDF123'),
1 => array('code' => 'ASDF124')
);
foreach ($array as $codes) {
if (in_array($input, $codes)) {
return true;
}
}
return false;
}
$needle = 'ASDF123';
$ary = Array(
Array('code' => 'ASDF123'),
Array('code' => 'ASDF124')
);
$_ = "return (\$a['code']='".addslashes($needle)."');";
if (count(array_filter($ary[0],create_function('$a',$_))) > 0)
//true
I THINK (only because you use code twice, so I assume that's not the search field--or it's a semantics issue). If it is semantics, as everyone else has already suggested, try array_key_exists.