I have this array. I want to extract to a new one array the content of only one of this array ([choices]). How can i do it in php?
Array
(
[0] => Array
(
[key] => field_54df3275b708a
[label] => Idioma
[name] => idioma
[type] => select
[instructions] =>
[required] => 0
[choices] => Array
(
[Catalan] => Catalan
[Castellano] => Castellano
[Ingles] => Ingles
)
[default_value] =>
[allow_null] => 0
[multiple] => 0
[conditional_logic] => Array
(
[status] => 0
[rules] => Array
(
[0] => Array
(
[field] => null
[operator] => ==
[value] =>
)
)
[allorany] => all
)
[order_no] => 0
)
)
I try this code (i think that's its a bad code):
foreach($array as $k=>$v){
if (is_array($v)){
foreach($v as $l=>$w){
if ($w){
foreach($w as $s=>$t){
$idiomas[]=$t.'<br />';
}
}
}
}
}
But it saves [choices] and [conditional_logic] to new array, and i only want [choices]
Thankyou so much
$new_array_choices = $array[0]['choices'];
Took me awhile to create a test code fiddle. I had to manually recreate the array.
Since you take the key in every foreach all the time, you can use it to ensure it's the array you want :
foreach($array as $k=>$v) {
if (is_array($v)) {
foreach($v as $l=>$w) {
if ($w && $l == 'choices') { // $w is the wanted array
foreach($w as $s=>$t) {
$idiomas[]=$t.'<br />';
}
}
}
}
}
I'm not sure what you are testing with if ($w) though
Replace $arr with your actual array and it should work nonetheless.
// your array (replace)
$arr = array(
"required" => 0,
"choices" => array(
"Catalan" => "Catalan",
"Castellano" => "Castellano",
"Ingles" => "Ingles",
),
"default" => NULL,
);
// the empty resulting array
$new_arr = array();
foreach($arr["choices"] as $key)
array_push($new_arr, $arr["choices"][$key]);
// your resulting array
print_r($new_arr);
Your desired array is saved in the array $new_arr.
Related
I have this array:
ARRAY 1
Array
(
[0] => Array
(
[required] => Tip:
)
[1] => Array
(
[required] => Flux:
)
[2] => Array
)
ARRAY 2
Array
(
[0] => Array
(
[name] => Flux:
)
[1] => Array
(
[name] => Tip:
)
[2] => Array
(
[name] => Weight:
)
)
How insert data from array 1 to array 2 when value of name and required are same.
Data from array some time don't have same values of name and required.
On output of array 2 I want to display something when value of required exist.
I need this:
Array
(
[0] => Array
(
[name] => Flux:
[required] => Flux:
)
[1] => Array
(
[name] => Tip:
[required] => Tip:
)
[2] => Array
(
[name] => Weight:
[required] =>
)
)
I tried with this:
foreach($char as $key =>$value){
foreach($mandatory as $key =>$val){
$data[] = array("name" => $value->charact_name, "required" => $val);
}
}
But is not output what I expect! It show me diferent values on name and required
This question is not a technical problem and you needed a little more tries to achieve a true algorithm.
I did some modifications to your code. $key variable must be different for two foreachs. Based on your question new key required just added to $arr2.
$arr1 = [['required' => 'Tip:'], ['required' => 'Flux:']];
$arr2 = [['name' => 'Flux:'], ['name' => 'Tip:'], ['name' => 'Weight:']];
foreach($arr2 as $key2 => $value2) {
$arr2[$key2]['required'] = NULL;
foreach($arr1 as $value1)
if($value2['name'] == $value1['required']) {
$arr2[$key2]['required'] = $value1['required'];
break;
}
}
I tried this:
foreach($char as $key2 => $value2) {
foreach($mandatory as $value1)
if($value2->charact_name == $value1) {
$data[] = array("name" => $value2->charact_name, "required" => $value1);
}
}
But data array it show me name and required only for values that is in $mandatory array, I want to display all from $char and when value exist in $mandatory add [required]=> name of value from $mandatory
You can simply create it with nested loops which cause time complexity O(n*m). However if you use a Hashmap (array with key value) which get O(1) to search you can create it very fast by O(n+m) as below:
<?php
$arr1 = array(0 => array('name' => 'Flux'),1 => array('name' => 'Tip'),2 => array('name' => 'Weight'));
$arr2 = array(0 => array('required' => 'Tip'),1 => array('required' => 'Flux'),2 => array());
$arrkey = array();
foreach ($arr1 as $ix=>$value) {
$arrkey[$value['name']]=$ix;
}
$arr3 = $arr1;
foreach ($arr2 as $elem) {
if(!empty($elem) && array_key_exists($elem['required'],$arrkey)) {
$arr3[$arrkey[$elem['required']]]['required'] = $elem['required'];
}
}
print_r($arr3);
?>
Try this online demo.
I've this type of array in PHP:
Array(
[100] => Array(
[1] => Array (
[AVA_Date] => 2019-04-18
[ROO_Id] => 100
[RAT_Id] => 9
)
[2] => Array (
[AVA_Date] => 2019-04-20
[ROO_Id] => 100
[RAT_Id] => 10
)
[4] => Array (
[AVA_Date] => 2019-04-21
[ROO_Id] => 100
[RAT_Id] => 10
)
[7] => Array (
[AVA_Date] => 2019-04-22
[ROO_Id] => 100
[RAT_Id] => 9
)
)
)
I would like to merge items on ROO_Id and RAT_Id.
Then, for the AVA_Date, I need to list them under a new array in the current array.
So, the desired output is:
Array(
[100] => Array(
[0] => Array (
[AVA_Date] => Array (
[0] => 2019-04-18
[1] => 2019-04-22
)
[ROO_Id] => 100
[RAT_Id] => 9
)
[1] => Array (
[AVA_Date] => Array (
[0] => 2019-04-20
[1] => 2019-04-21
)
[ROO_Id] => 100
[RAT_Id] => 10
)
)
)
Here what I have tried:
$newArrOtherRooms = array_reduce($newArr, function($acc, $val) {
$room = array_search($val['ROO_Id'], array_column($acc, 'ROO_Id'));
$rate = array_search($val['RAT_Id'], array_column($acc, 'RAT_Id'));
if($rate == $room && $room > -1) {
array_push($acc[$room]['AVA_Date'], $val['AVA_Date']);
}
else {
$new_arr = $val;
$new_arr['AVA_Date'] = [$val['AVA_Date']];
array_push($acc, $new_arr);
}
return $acc;
},[]);
But it doesn't work like I want.
There are a couple of issues with your code. Firstly, you need to wrap the array_reduce with a foreach over the outer level of $newArr. Secondly, your call to array_search doesn't consider the fact that a ROO_Id or RAT_Id value might exist more than once in the array, as it only returns the first key at which it finds the value. To work around this, you can use array_keys to get an array of key values for each ROO_Id and RAT_Id value, and then take the intersection of those two arrays using array_intersect to see if both are present in the same element. If so, you update that element, otherwise you create a new one:
foreach ($newArr as $key => $array) {
$newArrOtherRooms[$key] = array_reduce($array, function($acc, $val) {
$room = array_keys(array_column($acc, 'ROO_Id'), $val['ROO_Id']);
$rate = array_keys(array_column($acc, 'RAT_Id'), $val['RAT_Id']);
$common = array_intersect($room, $rate);
if(!empty($common)) {
array_push($acc[current($common)]['AVA_Date'], $val['AVA_Date']);
}
else {
$new_arr = $val;
$new_arr['AVA_Date'] = [$val['AVA_Date']];
array_push($acc, $new_arr);
}
return $acc;
},[]);
}
print_r($newArrOtherRooms);
Output:
Array(
[100] => Array(
[0] => Array (
[AVA_Date] => Array (
[0] => 2019-04-18
[1] => 2019-04-22
)
[ROO_Id] => 100
[RAT_Id] => 9
)
[1] => Array (
[AVA_Date] => Array (
[0] => 2019-04-20
[1] => 2019-04-21
)
[ROO_Id] => 100
[RAT_Id] => 10
)
)
)
Demo on 3v4l.org
There is absolutely no reason to be making all of those iterated function calls.
Use a nested loop to iterate the subset of data for each room, group on the room "rate id", and push all "available date" values into a subarray in the respective group. When the subset of data is fully iterated, push its grouped data into the result array.
Code: (Demo)
$result = [];
foreach ($newArr as $rooId => $rows) {
$groups = [];
foreach ($rows as $row) {
if (!isset($groups[$row['RAT_Id']])) {
$row['AVA_Date'] = (array) $row['AVA_Date'];
$groups[$row['RAT_Id']] = $row;
} else {
$groups[$row['RAT_Id']]['AVA_Date'][] = $row['AVA_Date'];
}
}
$result[$rooId] = array_values($groups);
}
var_export($result);
Output:
array (
100 =>
array (
0 =>
array (
'AVA_Date' =>
array (
0 => '2019-04-18',
1 => '2019-04-22',
),
'ROO_Id' => 100,
'RAT_Id' => 9,
),
1 =>
array (
'AVA_Date' =>
array (
0 => '2019-04-20',
1 => '2019-04-21',
),
'ROO_Id' => 100,
'RAT_Id' => 10,
),
),
)
I have on array of data in below.
Array
(
[0] => Array
(
[0] => Array
(
[rating] => 4
[review] => nice
)
[1] => Array
(
[rating] => 2
[review] => good
)
)
)
We customize above array and need to my custom array .
Need out put like below array. array always need 5 to 1 key because i am using this array for rating & review functionality.
Array
(
[0] => Array
(
[5] => Array
(
[rating] => 0
[review] => ""
)
[4] => Array
(
[rating] => 4
[review] => nice
)
[3] => Array
(
[rating] => 0
[review] => ""
)
[2] => Array
(
[rating] => 2
[review] => "good"
)
[1] => Array
(
[rating] => 0
[review] => ""
)
)
)
I managed to self-solve. Please find below solution as per output.
$arr1 = array(array("rating"=>4,"review"=>"nice"),array("rating"=>2,"review"=>"good"));
$final =a rray();
for ($i=5; $i>=1; $i--) {
foreach ($arr1 as $key =>$val) {
if ($val['rating']==$i) {
$final[$i] = array("rating"=>$val['rating'],"review"=>$val['review']);
break;
} else {
$final[$i] = array("rating"=>0,"review"=>"");
}
}
}
print_r($final);
Iterate each top level array (if you don't have multiple top level arrays, then you should consider restructuring your array structure to be more concise)
call array_column() on the level2 array so that the rating values are assigned as keys for their respective subarray.
Iterate in descending order from 5 to 1 while conditionally saving data to the output array.
Code: (Demo)
$input = [
[
['rating' => 4, 'review' => 'nice'],
['rating' => 2, 'review' => 'good']
]
];
foreach ($input as $x => $level2) {
$keyed = array_column($level2, null, 'rating'); // setup more efficient lookup
for($i = 5 ; $i > 0 ; --$i) {
$result[$x][$i] = isset($keyed[$i]) ? $keyed[$i] : ['rating' => 0, 'review' => ''];
}
}
var_export($result);
// output is as desired
I have an array like below: all the values I am getting one array only, but I don't want this way. This is the best way to do so, in php or jQuery both languages are ok for me
Array
(
[0] => Array
(
[val] => facebook
)
[1] => Array
(
[val] => snapchat
)
[2] => Array
(
[val] => instagram
)
[3] => Array
(
[expenses] => 986532
)
[4] => Array
(
[expenses] => 45456
)
[5] => Array
(
[expenses] => 56230
)
[6] => Array
(
[social_id] => 15
)
[7] => Array
(
[social_id] => 16
)
[8] => Array
(
[social_id] => 17
)
)
and I want to output like this..
$result = array(
array(
"val" => "Facebook",
"expenses" => "84512",
"social_id" => 1
),
array(
"val" => "Instagram",
"expenses" => "123",
"social_id" => 2
)
);
but this should be dynamic, the length of the above array can be varies
You can merge the arrays to one and use array_column to get all vals or expenses in a separate array.
Then foreach one array and build the new array with the key.
//$a = your array
// Grab each column separate
$val = array_column($a, "val");
$expenses= array_column($a, "expenses");
$social_id = array_column($a, "social_id");
Foreach($val as $key => $v){
$arr[] = [$v, $expenses[$key], $social_id[$key]];
}
Var_dump($arr);
https://3v4l.org/nVtDf
Edit updated with the 'latest' version of the array. My code works just fine with this array to without any changes.
to get that array style you can do it by hand for each array
function test(array ...$arr)
{
$result = array();
foreach ($arr as $key => $pair) {
foreach ($pair as $item => $value) {
$result[$item] = $value;
}
}
return $result;
}
$arr1 = test( ['facebook' => 1], ['expenses' => 100]);
print_r($arr1);
/* Array (
[facebook] => 1,
[expenses] => 100
)
*/
$arr2 = test( $arr1, ['more info' => 'info'] );
print_r($arr2);
/* Array (
[facebook] => 1,
[expenses] => 100,
[more info] => info
)
*/
you can pass it any number of
['Key' => 'Pair']
array('Key' => 'Pair')
or even a previous made array and it will add them up into 1 big array and return it
how can i count an element if it appears more than once in the same array?
I already tried with array_count_values, but it did not work, is it beacuse i got more than one key and value in my array?
This is my output from my array (restlist)
Array (
[0] => Array ( [restaurant_id] => 47523 [title] => cafe blabla)
[1] => Array ( [restaurant_id] => 32144 [title] => test5)
[2] => Array ( [restaurant_id] => 42154 [title] => blabla2 )
[3] => Array ( [restaurant_id] => 32144 [title] => test5)
[4] => Array ( [restaurant_id] => 42154 [title] => blabla2 )
)
I want it to count how many times the same element appears in my array and then add the counted value to my newly created 'key' called hits in the same array.
Array (
[0] => Array ( [restaurant_id] => 47523 [title] => cafe blabla [hits] => 1)
[1] => Array ( [restaurant_id] => 32144 [title] => test5 [hits] => 2)
[2] => Array ( [restaurant_id] => 42154 [title] => blabla2 [hits] => 2)
)
This is how i tried to do what i wanted.
foreach ($cooltransactions as $key)
{
$tempArrayOverRestaurants[]= $key['restaurant_id'];
}
$wordsRestaruants = array_count_values($tempArrayOverRestaurants);
arsort($wordsRestaruants);
foreach ($wordsRestaruants as $key1 => $value1)
{
$temprestaurantswithhits[] = array(
'restaurant_id' => $key1,
'hits' => $value1);
}
foreach ($restlistas $key)
{
foreach ($temprestaurantswithhits as $key1)
{
if($key['restaurant_id'] === $key1['restaurant_id'])
{
$nyspisestedsliste[] = array(
'restaurant_id' => $key['restaurant_id'],
'title' => $key['title'],
'hits' => $key1['hits']);
}
}
}
I know this is probably a noob way to do what i want but i am still new at php..I hope you can help
Just try with associative array:
$input = array( /* your input data*/ );
$output = array();
foreach ( $input as $item ) {
$id = $item['restaurant_id'];
if ( !isset($output[$id]) ) {
$output[$id] = $item;
$output[$id]['hits'] = 1;
} else {
$output[$id]['hits']++;
}
}
And if you want to reset keys, do:
$outputWithoutKeys = array_values($output);