Search Arrays to Multidimensional Array - php

I have 2 dimensional array like
$events = array(
array(
'desc' => 'Cancer Webinar',
'date' => '20201219'
),
array(
'desc' => 'CSR Management',
'date' => '20200812'
),
array(
'desc' => 'Company Anniversary',
'date' => '20200309'
)
);
$look = array('20201219','20200309');
result: array('Cancer Webinar','Company Anniversary');
The function call search from array list ($look) then find it to $events.
From the code above shoud return:
array('Cancer Webinar','Company Anniversary');

If the second array will just search by date use the following code
function search_from_array($array, $events) {
$result = [];
foreach($events as $event) {
if(in_array($event['date'], $array)) {
array_push($result, $event['desc']);
}
}
echo json_encode($result);
}
search_from_array($look, $events);
you can develop it more to can search with any key in the multidimensional array.
in case you want to search but many keys just add OR in the condition and make the same code for other keys like this
if(in_array($event['date'], $array) || in_array($event['desc'], $array))

You can make $look a dict, then check if the date key exist.
$events = array(
array(
'desc' => 'Cancer Webinar',
'date' => '20201219'
),
array(
'desc' => 'CSR Management',
'date' => '20200812'
),
array(
'desc' => 'Company Anniversary',
'date' => '20200309'
)
);
$look = array('20201219','20200309');
$look_dic = array_flip($look);
foreach($events as $event){
if(isset($look_dic[$event["date"]])){
$result[] = $event["desc"];
}
}
var_dump($result);

Related

array_intersect different value

im using array_intersect for comparing 2 array
$myArray = array(
array(
'site_id' => 'S6407',
'tssr_id' => 'TSSRBOQ-200204-0145-59'
),
array(
'site_id' => 'S5910',
'tssr_id' => 'TSSRBOQ-200204-0145-8'
),
);
// $items_tssr is get from another variable
foreach ($items_tssr as $key => $value) {
$array_validate[] = array(
'site_id' => $value['site_id'],
'tssr_id' => $value['no_tssr_boq_site']
);
}
$result = array_map('unserialize',
array_intersect(
array_map('serialize', $myArray), array_map('serialize', $array_validate)));
// if there are same
if(array_key_exists(0,$result)){
echo 'process this';
}else{
echo 'dont process this';
}
my problem is, the original $myArray is more than 'site_id' and 'tssr_id'
$myArray_origin = array(
'site_id' => 'S6407',
'tssr_id' => 'TSSRBOQ-200204-0145-59'
'site_name' => 'Site S6407',
'id_site_doc'=> '127361,
'implementation_id' => 'imp4121',
'status' => "implementation_created",
"endstate" => false
),
...
how do i process the $myArray_origin without throw away a few of the value? because $array_validate is only have 2 value 'site_id' and 'tssr_id'
You could make use of array_filter + in_array instead. This will only keep the entries whose site_id and tssr_id are present in one of array_validate's own entries:
$result = array_filter($myArray, function (array $entry) use ($array_validate): bool {
return in_array([
'site_id' => $entry['site_id'],
'tssr_id' => $entry['tssr_id']
], $array_validate, true);
});
Demo: https://3v4l.org/4Qhmr

How to use a while loop result within three dimensional array in php?

I would like to pass a while loop result as a value to three dimensional array,i have tried but i couldn't get it.I am trying to solve this from few days.Any suggestions or answers are appreciated.Thank you
$messages = array(
'sender' => "akhil",
'messages' => array(
//////////////while loop starts
while($i < $data){
array(
'number' =>$data[$i],//////here i want to pass the while loop
variable
'text' => rawurlencode('Hello,.........')
)
$i++;
}
/////////////while loop ends
)
);
///the would like to get the below result
$messages = array(
'sender' => "akhil",
'messages' => array(
array(
'number' => 918xxxxxx,
'text' => rawurlencode('Hello,------')
),
array(
'number' => 9196xxxxxx,
'text' => rawurlencode('Hello,----')
)
), array(
'number' => 919xxxxx,
'text' => rawurlencode('Hello,----')
)
)
);
You just need to create the array outside the while loop and then push values into it inside the loop. Your code is almost there...
$messages = array('sender' => "akhil",
'messages' => array()
);
while ($i < count($data)) {
$messages['messages'][] = array('number' => $data[$i],
'text' => rawurlencode('Hello,.........'));
$i++;
}
Demo on 3v4l.org
What you are looking for is called an Anonymous function.
You can achieve your expected behavior by doing this:
'messages' => (function(){
$res = [];
while($i < $data){
$res[] = [
'number' =>$data[$i],//////here i want to pass the while loop variable
'text' => rawurlencode('Hello,.........')
];
$i++;
}
return $res;
})(),
...
I do not know the exact structure of your data, but I would swap the while for an array_map(). It would look like this:
'messages' => array_map(function($d){
return [
'number' =>$d,
'text' => rawurlencode('Hello,.........')
]
},$data),
...
Hohpe that helps,

How to extract the relevant elements from this array of associative arrays?

I have the following challenging array of associative arrays in php.
array(
(int) 0 => array(
'table' => array(
'venue' => 'venue1',
'name' => 'name1'
)
),
(int) 1 => array(
'table' => array(
'venue' => 'venue1',
'name' => 'name2'
)
),
(int) 2 => array(
'table' => array(
'venue' => 'venue2',
'name' => 'name3'
)
),
(int) 3 => array(
'table' => array(
'venue' => 'venue3',
'name' => 'name4'
)
)
)
I want to extract a list of relevant names out based on the venue. I would like to implement a function ExtractNameArray($venue) such that when $venue=='venue1', the returned array will look like array('name1', 'name2')
I have been cracking my head over this. I am starting with $foreach and am stuck. How can this be done in php? Thank you very much.
first, you have to pass the array with the data to the function
second, the name of the function should start with lower character (php conventions)
try this
function extractNameArray($array, $venue) {
$results = array();
foreach($array as $key=>$value) {
if(isset($value['table']['venue'])&&$value['table']['venue']==$venue) {
isset($value['table']['name']) && $results[] = $value['table']['name'];
}
}
return $results;
}
function ExtractNameArray($venue)
{
$array = array(); // your array
$return_array = array();
foreach($array as $arr)
{
foreach($arr['table'] as $table)
{
if($table['venue'] == $venue)
{
$return_array[]['name'] = $table['name'];
}
}
}
return $return_array;
}
You must define $array with you array. Good Luck

Know the element level in multidimensional array

Well, I am here again dealing with arrays in php. I need your hand to guide me in the right direction. Suppose the following array:
-fruits
--green
---limon
---mango
--red
---apple
-cars
--ferrari
---enzo
----blue
----black
---318
--lamborg
---spider
---gallardo
----gallado-96
-----blue
-----red
-----gallado-98
The - (hyphen) symbol only illustrates the deep level.
Well, I need to build another array (or whatever), because it should be printed as an HTML select as below:
-fruits
--green
---limon
---mango
--red
---apple
-cars
--ferrari
---enzo
----blue
----black
---318
--lamborg
---spider
---gallardo
----gallado-96
-----blue
-----red
-----gallado-98
Looks that for each level element, it should add a space, or hyphen to determinate that it belongs to a particular parent.
EDIT
The have provide an answer provideng my final code. The html select element will display each level as string (repeating the "-" at the begging of the text instead multi-level elements.
Here's a simple recursive function to build a select dropdown given an array. Unfortunately I'm not able to test it, but let me know if it works. Usage would be as follows:
function generateDropdown($array, $level = 1)
{
if ($level == 1)
{
$menu = '<select>';
}
foreach ($array as $a)
{
if (is_array($a))
{
$menu .= generateDropdown($a, $level+1);
}
else
{
$menu .= '<option>'.str_pad('',$level,'-').$a.'</option>'."\n";
}
}
if ($level == 1)
{
$menu = '</select>';
}
return $menu;
}
OK, I got it with the help of #jmgardhn2.
The data
This is my array:
$temp = array(
array(
'name' => 'fruits',
'sons' => array(
array(
'name' => 'green',
'sons' => array(
array(
'name' => 'mango'
),
array(
'name' => 'banana',
)
)
)
)
),
array(
'name' => 'cars',
'sons' => array(
array(
'name' => 'italy',
'sons' => array(
array(
'name' => 'ferrari',
'sons' => array(
array(
'name' => 'red'
),
array(
'name' => 'black'
),
)
),
array(
'name' => 'fiat',
)
)
),
array(
'name' => 'germany',
'sons' => array(
array(
'name' => 'bmw',
)
)
),
)
)
);
Recursive function
Now, the following function will provide an array with items like [level] => [name]:
function createSelect($tree, $items, $level)
{
foreach ($tree as $key)
{
if (is_array($key))
{
$items = createSelect($key, $items, $level + 1);
}
else
{
$items[] = array('level' => $level, 'text' => $key);
}
}
return $items;
}
Calling the funcion
Now, call the function as below:
$items = createSelect($temp, array(), 0);
Output
If you iterate the final $items array it will look like:
1fruits
2green
3mango
3banana
1cars
2italy
3ferrari
4red
4black
3fiat
2germany
3bmw

Loop Through Specific Associative Array In PHP

I am trying to loop through only a specific sub array in PHP with foreach. Example array:
$testData = array(
$test1=array(
'testname'=>'Test This',
'testaction'=>'create user',
$testData = array(
'item'=>'value',
'foo'=>'bar',
'xyz'=>'value'
),
$anotherArray = array()
),
$test2=array(
'testname'=>'Test That',
'testaction'=>'get user',
$testData = array(
'item'=>'value',
'foo'=>'bar',
'xyz'=>'value'
),
$anotherArray = array()
)
);
And now I am going to go through each test and set some logic based on the name and action, but then need to do several tests on the data. Not sure how to only get $test1's $testData and not $test1's $anotherArray data. I have the following but it doesn't work:
foreach($testData as $test => $section){
foreach($section['testData'] as $field => $value){
\\code
}
}
Any help is appreciated! Thanks!
Try this instead:
$testData = array(
'test1'=>array(
'testname'=>'Test This',
'testaction'=>'create user',
'testData' => array(
'item'=>'value',
'foo'=>'bar',
'xyz'=>'value'
),
'anotherArray' => array()
),
'test2'=>array(
'testname'=>'Test That',
'testaction'=>'get user',
'testData' => array(
'item'=>'value',
'foo'=>'bar',
'xyz'=>'value'
),
'anotherArray' => array()
)
);

Categories