i have a string this one: position1, position2
Basically i want to have this kind of structure -
array(
array('position' => 'position 1'),
array('position' => 'position 2')
)
i have tried this so far.
$positions = explode(',', "position1, position2");
$modPoses = [];
foreach($positions as $pose):
$modPoses['position'] = $pose;
endforeach;
print_r($modPoses);
Output:
Array ( [position] => position2 )
How can i get desired(mentioned above) array structure?
Thank you.
I guess that what You want is:
array(
array('position' => 'position 1'),
array('position' => 'position 2')
)
If that is so, You can use:
array_map(function ($i) { return array('position' => $i); }, explode(',', 'position 1, position 2'))
It does not make any sense that you assign two values to same index but let me give you a solution. If you use 2d associative array then you can do it in this way
$counter = 0; //initialize counter here
foreach($positions as $pose):
$modPoses[$counter]['position'] = $pose;
$counter++;
endforeach;
Related
I have to merge (inject) an array in between another array.
Injected array is adding an additional level at the top.
Actual code is different, but here I have created a simple example to illustrate the issue I am facing.
Here is the sample code:
$mid_array = [
'heading3' => 'Heading 3',
'heading4' => 'Heading 4'
];
$main_array = [
'heading1' => 'Heading 1',
'heading2' => 'Heading 2',
$mid_array,
'heading5' => 'Heading 5'
];
echo '<pre>'; print_r($main_array); echo '</pre>';
Output I am getting
Array
(
[heading1] => Heading 1
[heading2] => Heading 2
[0] => Array
(
[heading3] => Heading 3
[heading4] => Heading 4
)
[heading5] => Heading 5
)
This is what exactly I need
Array
(
[heading1] => Heading 1
[heading2] => Heading 2
[heading3] => Heading 3
[heading4] => Heading 4
[heading5] => Heading 5
)
Based on the assumption that your arrays might change but will continue to have keys like heading1, heading2 this would be my solution
$newArray = array_merge($main_array,$mid_array);
ksort($newArray);
this will return the array you need.
I think you are looking for array_splice, as such:
array_splice($main_array, 2, 0, $mid_array);
Note: array_splice does not preserve keys, if keys are important to you, use following:
function array_insert(&$input, array $arrayToAdd, int $atPosition) {
$before = array_slice($input, 0, $atPosition, true);
$after = array_slice($input, $atPosition, null, true);
$input = $before + $arrayToAdd + $after;
}
Usage
array_insert($main_array, $mid_array, 2);
I think you are looking for the array_merge functionality.
http://php.net/manual/en/function.array-merge.php
You can use array_reduce:
$after = 'heading2';
$result = array_reduce(
array_keys($main_array),
function ($carry, $key) use ($main_array, $after, $mid_array) {
$carry[$key] = $main_array[$key];
return $key === $after
? array_merge($carry, $mid_array)
: $carry;
},
[]
);
Here is the demo.
If key ordering presents a problem (with something like array_merge) you can flatten the inserted array by walking it recursively. You walk along the tips plucking what you need as you go.
<?php
$insert = [
'foo' => 'And it\'s been the ruin of many a poor boy',
'bar' => 'And god I know I\'m one'
];
$inserted = [
'big' => 'There is a house in New Orleans',
'fat' => 'They call the rising sun',
$insert,
'mama' => 'My mother was a taylor'
];
$flattened = [];
array_walk_recursive(
$inserted,
function($v, $k) use (&$flattened) {
$flattened[$k] = $v;
}
);
var_export($flattened);
Output:
array (
'big' => 'There is a house in New Orleans',
'fat' => 'They call the rising sun',
'foo' => 'And it\'s been the ruin of many a poor boy',
'bar' => 'And god I know I\'m one',
'mama' => 'My mother was a taylor',
)
I have the following string: "1,3,4,7" which I need to explode into an Array in the following format:
$data = array(
array(
'id' => 1
),
array(
'id' => 3
),
array(
'id' => 4
),
array(
'id' => 7
),
);
This seems to be causing me a lot more pain than I'd have thought. Can anyone kindly assist please?
You can use a combination of array_map() and explode(): First you create an array with the values and than you map all these values to the format you need in a new array.
Something like:
$vals = "1,3,4,7";
$map = array_map(function($val) {
return array('id' => $val);
}, explode(',', $vals));
var_dump($map);
An example.
Firstly you explode the string to get the values in an array. Then you iterate through the array and set the data as array to another array
$string = "1,2,3,4";
$array = explode(",", $string);
$data = array();
foreach($array as $arr){
$data[] = array('id' => $arr);
}
<?php
$myArray=explode(",","1,3,5,7");
$result=array();
foreach($myArray as $key=>$arr)
{
$result[$key]['id']=$arr;
}
print_r($result);
?>
Here is a thinking-outside-the-box technique that doesn't require a loop or iterated function calls.
Form a valid query string with the desired structure and parse it. The empty [] syntax will generate the indexes automatically.
Code: (Demo)
$vals = "1,3,4,7";
$queryString = 'a[][id]=' . str_replace(',', '&a[][id]=', $vals);
parse_str($queryString, $output);
var_export($output['a']);
Output:
array (
0 =>
array (
'id' => '1',
),
1 =>
array (
'id' => '3',
),
2 =>
array (
'id' => '4',
),
3 =>
array (
'id' => '7',
),
)
I have two associative arrays
$reference = array(
'type_drink' => 'value',
'type_plate' => 'value',
'type_fork' => 'value',
'non_type' => 'value'
);
$target = array(
'type_plate' => 'value other',
'type_drink' => 'value other'
);
What's a nice way to re-order target to match $reference order of keys and ignoring keys that are not present in $target so that the final
$target = array(
'type_drink' => 'value other',
'type_plate' => 'value other'
);
Not sure if this is what you need, but here's what I interpret what you're asking for.
foreach($reference as $key => $val)
{
if(isset($target[$key]))
$tmp[$key] = $target[$key];
}
$target = $tmp;
http://php.net/manual/en/function.array-intersect-key.php and http://php.net/manual/en/function.ksort.php
ksort(array_intersect_key($target, $reference));
so I'm trying to write a method that will merge all the arrays with a certain key value, but the problem I'm running into is that when I try and unset the array, so that there are not duplicate results it skips over several things, which is confusing me. so any advice on how I can improve this method would be greatly appreciated. the other question I have.. is there a way to check if each of these arrays have all 4 keys that I'm looking for.
'Release Date' =>
'Spreadsheet and Flyer Month' =>
'Advertise in Monthly Update' =>
'Feature in Catalog' =>
so what I'm doing is merging arrays with the same id in the db, so I don't have to do some really nasty SQL querys, but I'm wondering if there's a way of making sure that all 4 of these keys will be in every result... and if there is a value associated with one or however many.. my method will add the value to its key, and if there is no value associated with the key it will just make a empty string.
protected function array_with_same_val($array, $key) {
for($i = 0; $i < count($array); $i++) {
for($j = 1; $j < count($array); $j++) {
if(isset($array[$j]) && isset($array[$i]) && $array[$i][$key]==$array[$j][$key]) {
$temp = array_merge($array[$i], $array[$j]);
$array[$i] = $temp;
//unset($array[$j]);
}
}
}
return $array;
}
Here is a sample of my array (there will be a lot more values, this is just to give an idea):
'0' => array
(
'Release Date' => 'September 1, 2013',
'cp_id' => '112960'
),
'1' => array
(
'Spreadsheet and Flyer Month' => 'September 1, 2013',
'cp_id' => '112960'
),
'2' => array
(
'Advertise in Monthly Update' => 'September 1, 2013',
'cp_id' => '112960'
),
'3' => array
(
'Release Date' => 'September 1, 2013',
'cp_id' => '109141'
),
);
any help on this would be greatly appreciated.
Try this ($input is the array you provided above) ...
$output = array();
$requiredKeys = array('Release Date' => '', 'Spreadsheet and Flyer Month' => '', 'Advertise in Monthly Update' => '', 'Feature in Catalog' => '');
foreach ($input as $item) {
if (array_key_exists($item['cp_id'], $output)) {
$output[$item['cp_id']] = array_merge($output[$item['cp_id']], $item);
} else {
$output[$item['cp_id']] = array_merge($requiredKeys, $item);
}
}
$output = array_values($output);
The array_values call at the bottom is just to remove the string keys from the array.
Say for example you just queried a database and you recieved this 2D array.
$results = array(
array('id' => 1, 'name' => 'red' , 'spin' => 1),
array('id' => 2, 'name' => 'green', 'spin' => -1),
array('id' => 3, 'name' => 'blue' , 'spin' => .5)
);
I often find myself writing loops like this.
foreach($results as $result)
$names[] = $result['name'];
My questions is does there exist a way to get this array $names without using a loop? Using callback functions count as using a loop.
Here is a more generic example of getting every field.
foreach($results as $result)
foreach($result as $key => $value)
$fields[$key][] = $value;
As of June 20th in PHP-5.5 there is a new function array_column
For example:
$records = array(
array(
'id' => 2135,
'first_name' => 'John',
'last_name' => 'Doe'
),
array(
'id' => 3245,
'first_name' => 'Sally',
'last_name' => 'Smith'
),
array(
'id' => 5342,
'first_name' => 'Jane',
'last_name' => 'Jones'
),
array(
'id' => 5623,
'first_name' => 'Peter',
'last_name' => 'Doe'
)
);
$firstNames = array_column($records, 'first_name');
print_r($firstNames);
Will return
Array
(
[0] => John
[1] => Sally
[2] => Jane
[3] => Peter
)
There are even more examples in the above mentioned link.
I voted #Devon's response up because there really isn't a way to do what you're asking with a built-in function. The best you can do is write your own:
function array_column($array, $column)
{
$ret = array();
foreach ($array as $row) $ret[] = $row[$column];
return $ret;
}
Starting PHP 5.3, you can use this pretty call with lambda function:
$names = array_map(function ($v){ return $v['name']; }, $results);
This will return array sliced by 'name' dimension.
Simply put, no.
You will need to use a loop or a callback function like array_walk.
I did more research on this and found that ruby and prototype both have a function that does this called array_pluck,2. It's interesting that array_map has a second use that allows you to do the inverse of what i want to do here. I also found a PHP class someone is writing to emulate prototypes manipulation of arrays.
I'm going to do some more digging around and if I don't find anything else I'll work on a patch to submit to the internals#lists.php.net mailing list and see if they will add array_pluck.
For those of you that cannot upgrade to PHP5.5 right now and need this function, here is an implementation of array_column.
function array_column($array, $column){
$a2 = array();
array_map(function ($a1) use ($column, &$a2){
array_push($a2, $a1[$column]);
}, $array);
return $a2;
}
If you are running a version of PHP before 5.5 and array_column(), you can use the official replacement in plain PHP:
https://github.com/ramsey/array_column
I think this will do what you want
array_uintersect_uassoc
You would have to do something like this
$results = array(
array('id' => 1, 'name' => 'red' , 'spin' => 1),
array('id' => 2, 'name' => 'green', 'spin' => -1),
array('id' => 3, 'name' => 'blue' , 'spin' => .5)
);
$name = array_uintersect_uassoc( $results, array('name' => 'value') , 0, "cmpKey");
print_r($name);
//////////////////////////////////////////////////
// FUNCTIONS
//////////////////////////////////////////////////
function cmpKey($key1, $key2) {
if ($key1 == $key2) {
return 0;
} else {
return -1;
}
}
However, I don't have access to PHP5 so I haven't tested this.
You could do:
$tmp = array_flip($names);
$names = array_keys($tmp);
This is fast function alternative of array_column()
if(!function_exists('array_column')) {
function array_column($element_name) {
$ele = array_map(function($element) {
return $element[$element_name];
}, $a);
return $ele;
}
}
other alternative
function transpose(array $array): array
{
$out = array();
foreach ($array as $rowkey => $row) {
foreach ($row as $colkey => $col) {
$out[$colkey][$rowkey] = $col;
}
}
return $out;
}
function filter_columns(array $arr, string ...$columns): array
{
return array_intersect_key($arr, array_flip($columns));
}
test
$results = array(
array('id' => 1, 'name' => 'red' , 'spin' => 1),
array('id' => 2, 'name' => 'green', 'spin' => -1),
array('id' => 3, 'name' => 'blue' , 'spin' => .5)
);
var_dump(filter_columns(transpose($results),'name'));
var_dump(filter_columns(transpose($results),'id','name'));
var_dump(filter_columns(transpose($results),'id','spin'));