I got this array named $records
:
Array
(
[0] => Array
(
[id] => 14
[name] => name1
[publisher] => Dieter
[date] => 2022-07-29
[text] => blablablablablablablablablabblablablablablablablablablablablablablablabla
)
[1] => Array
(
[id] => 16
[name] => name2
[publisher] => Dieter
[date] => 2022-07-28
[text] => awhduawohduawohduawhduawuhdawhduaiwd
)
[2] => Array
(
[id] => 17
[name] => name3
[publisher] => Dieter
[date] => 2022-07-30
[text] => blub
)
[3] => Array
(
[id] => 18
[name] => name4
[publisher] => Dieter
[date] => 2022-07-31
[text] => awdawdw
)
)
and then I want to filter them by their ids($ids=[14,16]
):
$articles = array();
foreach ($records as $article) {
if (in_array($article['id'], $ids)) { //alg select only one article
$articles = array_merge($articles, $article);
}
}
return $articles;
and the Output should look like this:
Array
(
[0] => Array
(
[id] => 14
[name] => name1
[publisher] => Dieter
[date] => 2022-07-29
[text] => blablablablablablablablablabblablablablablablablablablablablablablablabla
)
[1] => Array
(
[id] => 16
[name] => name2
[publisher] => Dieter
[date] => 2022-07-28
[text] => awhduawohduawohduawhduawuhdawhduaiwd
)
)
But I got this:
Array
(
[id] => 16
[name] => name2
[publisher] => Dieter
[date] => 2022-07-28
[text] => awhduawohduawohduawhduawuhdawhduaiwd
)
This command doesnt work because I get a diffrent structure:
array_merge_recursiv()
CodePudding user response:
$articles = array();
foreach ($records as $article) {
if (in_array($article['id'], $ids)) { //alg select only one article
$articles[] = $article;
}
}
return $articles;
array_merge
is not needed here, you can push a new entry in your table using $articles[]
.
You can also keep keys of the original table like that :
$articles = array();
foreach ($records as $key => $article) {
if (in_array($article['id'], $ids)) { //alg select only one article
$articles[$key] = $article;
}
}
return $articles;
CodePudding user response:
function array_diff_column_values($rawArray, $searchArray, $columnName = 'id') {
$result = [];
foreach($rawArray as $key => $value) {
if (isset($value[$columnName]) && in_array($value[$columnName], $searchArray)) {
$result[] = $value;
}
}
return $result;
}
echo "<pre>";
print_r(array_diff_column_values($records, [14,16]));
echo "</pre>";