lumen, how can I not display the same name? - php

I have the code if there is the same name in 2nd foreach, then the same name is not displayed, but I don't know how to keep the same name not displayed?.
$arr = [];
foreach ($respon_tel['item'] as $item) {
$proyek = [
'nama_proyek' => $item['judul_kontrak'],
'from' => 'Another API'
];
foreach($model as $m){
if(trim(strtolower($item['judul_kontrak'])) == trim(strtolower($m['nama_proyek']))){
// ????
}
}
$arr[] = $proyek;
}
return $arr;

You can get all the nama_proyek's from the $model then you can check if the current $item's judul_kontrak is in that set:
$models = collect($model)
->map(fn ($i) => trim(strtolower($i['nama_proyek'])));
foreach ($respon_tel['item'] as $item) {
if (! $models->contains(trim(strtolower($item['judul_kontrak'])))) {
$arr[] = [
'nama_proyek' => $item['judul_kontrak'],
'from' => 'Another API'
];
}
}
Or you could get creative with the Collection methods:
collect($respon_tel['item'])
->pluck('judul_kontrak', 'judul_kontrak')
->map($f = fn ($item) => trim(strtolower($item)))
->diff(
collect($model)->pluck('nama_proyek')->map($f)
)->map(function ($item, $key) {
return [
'nama_proyek' => $key,
'from' => 'Another API',
];
})->values();

Related

PHP Closure - Return an array with key / value

I use DomCrawler to grab some data, and I would like to know if I can get an array from a closure, here is my code :
$promises = $products
->each(function(Crawler $node) use ($client, $cookieJar) {
$href = $node->filter('a')->last()->attr('href');
return [
$href => $client->getAsync($this->config['url'] . $href, [
'cookies' => $cookieJar,
])
];
});
It will return me like :
$promises = [
['href_value' => Guzzle\Promise],
....
];
But I would like to have :
$promises = [
'href_value' => Guzzle\Promise,
....
];
How can I tranform the return statetement to have this result, something like this in my mind :
return ($href) => $client->getAsync($this->config['url'] . $href, [
'cookies' => $cookieJar,
]);
Transform your $promises to have flat array:
$flatPromises = [];
foreach ($promises as $promise) {
foreach ($promise as $key => $value) {
$flatPromises[$key] = $value;
}
}

PHP: Getting values from array1 with from nested arrays

I have two arrays. $array2 to check whether $array1 value exist in 'slug'.
$array1 = [
0 => "tenants",
1 => "modules",
];
$array2 = [
"child" => [
"prefix" => "tenants",
"slug" => "tenants",
"child" => [
[
"prefix" => "modules/{id}",
"slug" => "modules"
],
[
"prefix" => "fetch/{id}",
"slug" => "fetch"
],
],
],
];
My Code:
foreach ($array1 as $value) {
array_walk_recursive($array2['child'],
function ($item, $key) use (&$result, &$res, &$value) {
if ($key == "slug") {
if ($item == $value) {
$res[] = $item;
}
}
if ($key == 'prefix') {
$result[] = $item;
}
});
}
Here I used array_walk_recursive to check every if array1 is exist in slug. But i want to get also it's prefix.
In my code above It will not get the modules/{id} since it's not equal to slug.
Example:
$array1 = [
0 => "tenants",
1 => "modules",
];
Result:
array:3 [▼
1 => "tenants"
2 => "modules/{id}"
]
Code: https://3v4l.org/E18Uq
Happy coding.
You don't need to use array_walk_recursive just use custom function as:
function getFromChild($item, $asd) {
if (!is_array($item)) return [];
$res = [];
if ($item["slug"] == $asd) // if have slug check and add if needed
$res[] = $item['prefix'];
if (isset($item['child']))
foreach($item['child'] as $child) // for all child loop and add
$res = array_merge($res, getFromChild($child, $asd));
return $res;
}
Now you can call it with:
$res = [];
foreach ($array1 as $asd) {
$res = array_merge($res, getFromChild($array2, $asd));
}
Live example: 3v4l

I have a question about php search associative array

I have this ff. assoc array
$array = [
'school' => [
'college' => [
'nursing' => ['n1a', 'n2a', 'n3a', 'n4a'],
'hrm' => ['h1a', 'h2a', 'h3a', 'h4a'],
'tourism' => ['t1a', 't2a', 't3a', 't4a'],
'it' => ['i1a', 'i2a', 'i3a', 'i4a'],
],
'senior' => [],
],
'business' => [
'office' => [
'dep1' => ['team1', 'team2'],
'dep2' => ['team1', 'team2'],
'dep3' => ['team1', 'team2'],
'dep4' => ['team1', 'team2'],
],
],
]
And I have this code, but this only search first level array.
function searchItemsByKey($array, $key) {
$results = array();
if (is_array($array))
{
if (isset($array[$key]) && key($array)==$key){
$results[] = $array[$key];
}
foreach ($array as $sub_array){
$results = array_merge($results, $this->searchItemsByKey($sub_array, $key));
}
}
return $results;
}
All I want is to search all keys in this array that will result all arrays associated with keys like:
searchItemsByKey($array, 'hrm');
That will return:
['h1a', 'h2a', 'h3a', 'h4a']
Thanks.
You can use array_walk_recursive,
$result = [];
$search = "hrm";
function searchItemsByKey($array, $key)
{
$retArr = [];
if (is_array($array)) {
if (!empty($array[$key])) {
return $array[$key];
}
foreach ($array as $val) {
$retArr = array_merge($retArr, searchItemsByKey($val, $key));
}
}
return $retArr;
}
$temp = searchItemsByKey($array, 'hrm');
Demo.

Array to string conversion laravel 5.6

$data = $request->all();
if (!empty($data))
{
foreach ($data as $key => $value)
{
if($key === "_token")
{
continue;
}
$val = [
'questionnaire_id' => $questionnaire_id,
'question_id' => $key,
'answer' => $value
];
$answer = Answer::create($val);
}
}
This is my array
{
"_token": "URP1tlRfoD0RFMYIgVIyBX1AYaobDsQU2wnvxC1r",
"questionnaires_id": "5",
"questions": {
"2": "a",
"10": "3",
"11": "b",
"44": "2018-08-01"
}
}
this is my model class
class Answer extends Model
{
protected $fillable = [
'questionnaire_id', 'question_id', 'answer'
];
}
Change your code like this
$qs = $request->questions;
$qr = $request->questionnaires_id;
foreach ($qs as $k => $q)
{
$val = [
'questionnaire_id' => $qr,
'question_id' => $k,
'answer' => $q
];
$answer = Answer::create($val);
}
If you want to convert only array to string, You should use php function like json_encode()
To store array in DB/Model you can do this:
protected $casts = [
'answer' => 'array'
];
And $answer can be:
$answer = array($your_data);
You should follow this flow.
$data = $request->all();
if (!empty($data))
{
$questionnaires_id = 0;
$questions = [];
foreach ($data as $key => $value)
{
if($key === "_token")
{
continue;
}
if($key === "questionnaires_id")
{
$questionnaires_id = $value;
}
if($key === "questions")
{
$questions = $value;
}
}
foreach ($questions as $key => $value) {
$val = [
'questionnaire_id' => $questionnaires_id,
'question_id' => $key,
'answer' => $value
];
$answer = Answer::create($val);
}
}

PHP - Arrays and Foreach

I searched in Google and consulted the PHP documentation, but couldn't figure out how the following code works:
$some='name=Licensing Module;nextduedate=2013-04-10;status=Active|name=Test Addon;nextduedate=2013-04-11;status=Active';
function getActiveAddons($somet) {
$addons = array( );
foreach ($somet as $addon) {
if ($addon['status'] == 'Active') {
$addons[] = $addon['name'];
continue;
}
}
return $addons;
}
echo (count( getActiveAddons( $some ) ) ? implode( '<br />', getActiveAddons( $some ) ) : 'None');
The code always echo's None.
Please help me in this.
I don't know where you got this code from but you've initialized $some the wrong way. It is expected as an array like this:
$some = array(
array(
'name' => 'Licensing Module',
'nextduedate' => '2013-04-10',
'status' => 'Active'
),
array(
'name' => 'Test Addon'
'nextduedate' => '2013-04-11',
'status' => 'Active'
)
);
I guess the article you've read is expecting you to parse the original string into this format.
You can achieve this like this:
$string = 'name=Licensing Module;nextduedate=2013-04-10;status=Active|name=Test Addon;nextduedate=2013-04-11;status=Active';
$result = array();
foreach(explode('|', $string) as $record) {
$item = array();
foreach(explode(';', $record) as $column) {
$keyval = explode('=', $column);
$item[$keyval[0]] = $keyval[1];
}
$result[]= $item;
}
// now call your function
getActiveAddons($result);
$some is not an array so foreach will not operate on it. You need to do something like
$some = array(
array(
'name' => 'Licensing Module',
'nextduedate' => '2013-04-10',
'status' => 'Active'
),
array(
'name' => 'Test Addon',
'nextduedate' => '2013-04-11',
'status'=> 'Active'
)
);
This will create a multidimensional array that you can loop through.
function getActiveAddons($somet) {
$addons = array( );
foreach ($somet as $addon) {
foreach($addon as $key => $value) {
if ($key == 'status' && $value == 'Active') {
$addons[] = $addon['name'];
continue;
}
}
}
return $addons;
}
First, your $some variable is just a string. You could parse the string into an array using explode(), but it's easier to just start as an array:
$some = array(
array(
"name" => "Licensing Module",
"nextduedate" => "2013-04-10",
"status" => "Active",
),
array(
"name" => "Test Addon",
"nextduedate" => "2013-04-11",
"status" => "Active",
)
);
Now, for your function, you are on the right track, but I'll just clean it up:
function getActiveAddons($somet) {
if (!is_array($somet)) {
return false;
}
$addons = array();
foreach ($somet as $addon) {
if ($addon['status'] == 'Active') {
$addons[] = $addon['name'];
}
}
if (count($addons) > 0) {
return $addons;
}
return false;
}
And finally your output (you were calling the function twice):
$result = getActiveAddons($some);
if ($result === false) {
echo "No active addons!";
}
else {
echo implode("<br />", $result);
}

Categories