Here is my array
$myArray = Array(
[63145] => Array
(
[id] => 63145
[name] => banana
[type] => fruit
)
[244340] => Array
(
[id] => 244340
[name] => apple
[type] => fruit
)
[253925] => Array
(
[id] => 253925
[name] => portato
[type] => vegetable
)
[233094] => Array
(
[id] => 233094
[name] => carrot
[type] => vegetable
));
How do i loop through this and pull out the ids of all fruits, so i kan use them in another foreach loop?
maybe with a If statement, so that if(type == fruit) use the ids in the foreach loop.
I have tried to look through other questions but I can't figure out how to convert the answers to my array (I know I'm a noob)..
The naïve:
$fruitIds = [];
foreach ($myArray as $item) {
if ($item['type'] == 'fruit') {
$fruitIds[] = $item['id'];
}
}
The functional:
$fruitIds = array_column(
array_filter($myArray, function (array $i) { return $i['type'] == 'fruit'; }),
'id'
);
The more efficient functional:
$fruitIds = array_reduce($myArray, function (array $ids, array $i) {
return array_merge($ids, $i['type'] == 'fruit' ? [$i['id']] : []);
}, []);
You can do this using PHP's array_column and array_filter:
$fruit_ids = array_column(array_filter($arr, function($item, $index) {
return $item['type'] == 'fruit';
}), 'id');
But also your array keys seem to be the same as your id values on the child arrays, so you could mix array_filter with array_keys:
$fruit_ids = array_keys(array_filter($arr, function($item, $index) {
return $item['type'] == 'fruit';
}));
Related
The main thing is multidimensional arrays can be random and I don't know exactly how many arrays inside in it. That why function should include recursion and checks does it have more array inside, example below can't do it without pre configuration. Appreciating any help
$arrays = array(
array(
'House' => 'Baratheon',
'Sigil' => 'A crowned stag',
'Motto' => 'Ours is the Fury',
),
array(
'Leader' => 'Eddard Stark',
'House' => 'Stark',
'Motto' => 'Winter is Coming',
'Sigil' => 'A grey direwolf'
),
array(
array('SomeArray' => 'You are cool'),
'House' => 'Lannister',
'Leader' => 'Tywin Lannister',
'Sigil' => 'A golden lion'
),
array(
'Q' => 'Z'
)
);
function next_element($array) {
foreach ($array as $some_type) {
if (is_array($some_type)) {
return true;
} else {
return false;
}
}
}
function check_in($inputs) {
foreach ($inputs as $position => $input) {
if (is_array($input) && next_element($input)) { // case with multidimentional array
check_in($input);
$check_in_result[] = "There are should be recursion!!!!!";
} else { // case with one simple array
$check_in_result[] = $input;
}
}
return $check_in_result;
}
Have tried with array_walk_recursive() but that function is working with all elements and returns as result one array with all keys and values. In this case it should be array(array1, array2, array3, array4) for next stage which is foreach loop.
As resutl it should be:
Array
(
[0] => Array
(
[House] => Baratheon
[Sigil] => A crowned stag
[Motto] => Ours is the Fury
)
[1] => Array
(
[Leader] => Eddard Stark
[House] => Stark
[Motto] => Winter is Coming
[Sigil] => A grey direwolf
)
[2] => Array
(
[SomeArray] => You are cool
)
[3] => Array
(
[House] => Lannister
[Leader] => Tywin Lannister
[Sigil] => A golden lion
)
[4] => Array
(
[Q] => Z
)
)
Try using a recursive function like this:
function parseMyArray($array) {
$result = [];
$row = [];
foreach($array as $key => $item) {
if (is_array($item)) {
$result = array_merge($result, parseMyArray($item));
} else {
$row[$key] = $item;
}
}
return !empty($row) ? array_merge($result, [$row]) : $result;
}
$result = parseMyArray($arrays);
print_r($result);
At each level of a function call, all scalar values with their keys are collected into one array as $row and merged with the $result of a nested function call.
fiddle
I'm new in array. I wish to print out the values of all possible [type] [label] [value]. I wish to do like "if there's a type with select, then display all labels with values"
Below is my array.
Array
(
[product_id] => 8928
[title] => Example of a Product
[groups] => Array
(
[8929] => Array
(
[8932] => Array
(
[type] => select
[label] => Section
[id] => pewc_group_8929_8932
[group_id] => 8929
[field_id] => 8932
[value] => Section 200
[flat_rate] => Array
(
)
)
)
)
[price_with_extras] => 0
[products] => Array
(
[field_id] => pewc_group_8929_9028
[child_products] => Array
(
[8945] => Array
(
[child_product_id] => Array
(
[0] => 8945
)
[field_id] => pewc_group_8929_9028
[quantities] => one-only
[allow_none] => 0
)
)
[pewc_parent_product] => 8928
[parent_field_id] => pewc_5d678156d81c6
)
)
The site is saying "
It looks like your post is mostly code; please add some more details." So here's my so-called lorem ipsum :D
You can use array_walk_recursive for the same,
array_walk_recursive($arr, function ($value, $key) {
// check if key matches with type, label or value
if (count(array_intersect([$key], ['type', 'label', 'value'])) > 0) {
echo "[$value] ";
}
});
Demo
Output
[select] [Section] [Section 200]
EDIT
You can modify the condition as,
if($key === 'type' && $value == 'select')
EDIT 1
array_walk_recursive($arr, function ($value, $key) {
if($key === 'type' && $value == 'select'){
echo "[$value] ";
}
});
EDIT 2
function search_by_key_value($arr, $key, $value)
{
$result = [];
if (is_array($arr)) {
if (isset($arr[$key]) && $arr[$key] == $value) {
$result[] = $arr;
}
foreach ($arr as $value1) {
$result = array_merge($result, search_by_key_value($value1, $key, $value));
}
}
return $result;
}
// find array by key = type and value = select
$temp = search_by_key_value($arr, 'type', 'select');
$temp = array_shift($temp);
print_r($temp);
echo $temp['label'];
echo $temp['value'];
Demo
I searched for my related topic, but didn't find a similar issue.
I have an array within an array and I have an array which I define as my ordering array.
[array1] => Array
(
[23456] => Array
(
[id] => 1
[info] => info
)
[78933] => Array
(
[id] => 1
[info] => info
)
)
and so on....
[orderarray] => Array
(
[0] => Array
(
[id] => 78933
)
[1] => Array
(
[id] => 23456
)
)
I would like to reorder array1 keys by the value of orderarray id.
So the first key should be then 78933 and not like in array1 23456.
Does anybody knows how to continue this?
I know to read the keys from array1.
foreach ($array1 as $key)
{
echo $key;
}
foreach ($orderarray as $key)
{
foreach ($key as $id => val)
{
echo $val;
}
}
So how can I merge both foreach together the best way?
Thank you so much!
You can use a custom key-sort function using uksort()
<?php
$array = array(
"23456" => array("id" => 1, "info" => "info"),
"78933" => array("id" => 1, "info" => "info")
);
$orderarray = array(
array("id" => 78933),
array("id" => 23456)
);
function customSort($a, $b) {
global $orderarray;
$_a = 0; $_b = 0;
foreach ($orderarray as $index => $order) {
$oid = intval($order['id']);
if ($oid == intval($a)) $_a = $index;
if ($oid == intval($b)) $_b = $index;
}
if ($_a == $_b) {
return 0;
}
return ($_a < $_b) ? -1 : 1;
}
uksort($array, "customSort");
print_r($array);
?>
How would I create a function that filters a two dimensional array by value?
Given the following array :
Array
(
[0] => Array
(
[interval] => 2014-10-26
[leads] => 0
[name] => CarEnquiry
[status] => NEW
[appointment] => 0
)
[1] => Array
(
[interval] => 2014-10-26
[leads] => 0
[name] => CarEnquiry
[status] => CALL1
[appointment] => 0
)
[2] => Array
(
[interval] => 2014-10-26
[leads] => 0
[name] => Finance
[status] => CALL2
[appointment] => 0
)
[3] => Array
(
[interval] => 2014-10-26
[leads] => 0
[name] => Partex
[status] => CALL3
[appointment] => 0
)
How would I filter the array to only show those arrays that contain a specific value in the name key? For example name = 'CarEnquiry'.
The resulting output would be:
Array
(
[0] => Array
(
[interval] => 2014-10-26
[leads] => 0
[name] => CarEnquiry
[status] => NEW
[appointment] => 0
)
[1] => Array
(
[interval] => 2014-10-26
[leads] => 0
[name] => CarEnquiry
[status] => CALL1
[appointment] => 0
)
)
EDIT
I forgot to mention that the search value should be interchangeable - i.e. name = 'CarEnquiry' or name = 'Finance'.
Use PHP's array_filter function with a callback.
$new = array_filter($arr, function ($var) {
return ($var['name'] == 'CarEnquiry');
});
Edit: If it needs to be interchangeable, you can modify the code slightly:
$filterBy = 'CarEnquiry'; // or Finance etc.
$new = array_filter($arr, function ($var) use ($filterBy) {
return ($var['name'] == $filterBy);
});
If you want to make this a generic function use this:
function filterArrayByKeyValue($array, $key, $keyValue)
{
return array_filter($array, function($value) use ($key, $keyValue) {
return $value[$key] == $keyValue;
});
}
<?php
function filter_array($array,$term){
$matches = array();
foreach($array as $a){
if($a['name'] == $term)
$matches[]=$a;
}
return $matches;
}
$new_array = filter_array($your_array,'CarEnquiry');
?>
Above examples are using the exact word match, here is a simple example for filtering array to find imprecise "name" match.
$options = array_filter($options, function ($option) use ($name) {
return strpos(strtolower($option['text']), strtolower($name)) !== FALSE;
});
array_filter is the function you need. http://php.net/manual/en/function.array-filter.php
Give it a filtering function like this:
function my_filter($elt) {
return $elt['name'] == 'something';
}
function multi_array_search_with_condition($array, $condition)
{
$foundItems = array();
foreach($array as $item)
{
$find = TRUE;
foreach($condition as $key => $value)
{
if(isset($item[$key]) && $item[$key] == $value)
{
$find = TRUE;
} else {
$find = FALSE;
}
}
if($find)
{
array_push($foundItems, $item);
}
}
return $foundItems;
}
This my function can use about this problem. You can use:
$filtered = multi_array_search_with_condition(
$array,
array('name' => 'CarEnquiry')
);
This will get your filtered items from your 2 dimensional array.
Let's say I have an array like this:
Array
(
[id] => 45
[name] => john
[children] => Array
(
[45] => Array
(
[id] => 45
[name] => steph
[children] => Array
(
[56] => Array
(
[id] => 56
[name] => maria
[children] => Array
(
[60] => Array
(
[id] => 60
[name] => thomas
)
[61] => Array
(
[id] => 61
[name] => michelle
)
)
)
[57] => Array
(
[id] => 57
[name] => luis
)
)
)
)
)
What I'm trying to do is to reset the keys of the array with keys children to 0, 1, 2, 3, and so on, instead of 45, 56, or 57.
I tried something like:
function array_values_recursive($arr)
{
foreach ($arr as $key => $value)
{
if(is_array($value))
{
$arr[$key] = array_values($value);
$this->array_values_recursive($value);
}
}
return $arr;
}
But that reset only the key of the first children array (the one with key 45)
function array_values_recursive($arr)
{
$arr2=[];
foreach ($arr as $key => $value)
{
if(is_array($value))
{
$arr2[] = array_values_recursive($value);
}else{
$arr2[] = $value;
}
}
return $arr2;
}
this function that implement array_values_recursive from array like:
array(
'key1'=> 'value1',
'key2'=> array (
'key2-1'=>'value-2-1',
'key2-2'=>'value-2-2'
)
);
to array like:
array(
0 => 'value1',
1 => array (
0 =>'value-2-1',
1 =>'value-2-2'
)
);
You use a recursive approach but you do not assign the return value of the function call $this->array_values_recursive($value); anywhere. The first level works, as you modify $arr in the loop. Any further level does not work anymore for mentioned reasons.
If you want to keep your function, change it as follows (untested):
function array_values_recursive($arr)
{
foreach ($arr as $key => $value)
{
if (is_array($value))
{
$arr[$key] = $this->array_values_recursive($value);
}
}
if (isset($arr['children']))
{
$arr['children'] = array_values($arr['children']);
}
return $arr;
}
This should do it:
function array_values_recursive($arr, $key)
{
$arr2 = ($key == 'children') ? array_values($arr) : $arr;
foreach ($arr2 as $key => &$value)
{
if(is_array($value))
{
$value = array_values_recursive($value, $key);
}
}
return $arr2;
}
Try this ,
function updateData($updateAry,$result = array()){
foreach($updateAry as $key => $values){
if(is_array($values) && count($values) > 0){
$result[$key] = $this->_updateData($values,$values);
}else{
$result[$key] = 'here you can update values';
}
}
return $result;
}
You can used php fnc walk_array_recursive
Here