How to check one single array value into another multiple value? - php

Hello Developer I am trying to check one single array into multiple array value and My exact requirement is the value of one array should be check in each indexes of second array and replace if same otherwise append it in new array.
My Two array was like this:-
One array:-
$array1 = array(
"extension_date" => "2017-05-19",
"extended_date" => "2017-05-27"
);
Second Array:-
$array2 = array(
0 => array(
"extension_date" => "2017-05-19",
"extended_date" => "2017-05-27"
),
1 => array(
"extension_date" => "2017-05-31",
"extended_date" => "2017-05-31"
),
);
I am try it from yesterday but it's not be succeed so please help me to solve out this issue.

You can make use of array_search and array_push. You don't need to replace if you find the search array in the main array since it's the exact same thing.
$search = [
"extension_date" => "2017-05-19",
"extended_date" => "2017-05-27"
];
$data = [
[
"extension_date" => "2017-05-19",
"extended_date" => "2017-05-27"
],
[
"extension_date" => "2017-05-31",
"extended_date" => "2017-05-31"
]
];
if (array_search($search, $data) === false) {
array_push($data, $search);
}
// $data contains $search if it's missing

Here we are using array_search if needle doesn't exist then we add that in array.
Try this code snippet here
<?php
ini_set('display_errors', 1);
$array1 = array(
"extension_date" => "2017-05-19",
"extended_date" => "2017-05-27"
);
$array2 = array(
0 => array(
"extension_date" => "2017-05-19",
"extended_date" => "2017-05-27"
),
1 => array(
"extension_date" => "2017-05-31",
"extended_date" => "2017-05-31"
),
);
if(array_search($array1, $array2)===false)
{
$array2[]=$array1;
}
print_r($array2);

Inputs:
$array1 = array(
"extension_date" => "2017-05-19",
"extended_date" => "2017-05-27"
);
$array2 = array(
array(
"extension_date" => "2017-05-19",
"extended_date" => "2017-05-27"
),
array(
"extension_date" => "2017-05-31",
"extended_date" => "2017-05-31"
),
);
Method:
if(!in_array($array1,$array2)){
$array2[]=$array1;
}
Since you are only checking to see if the subarray exists and you don't care about its key, it doesn't make sense to use array_search(). in_array() was specifically designed to return true false -- so use it!
var_export($array2) output:
array (
0 =>
array (
'extension_date' => '2017-05-19',
'extended_date' => '2017-05-27',
),
1 =>
array (
'extension_date' => '2017-05-31',
'extended_date' => '2017-05-31',
),
)

Related

Remove previous iteration's data from re-used array

I have two arrays, $array1 and $array2. $array2 is an array of arrays. For each subarray of $array2, I want to print $array1 but with additional entries that depend on whether the $array2 subarray has keys "a" or "c" with value 1. My code prints $array1 each loop, but there are additional entries in $array1 for the later iterations that I wasn't expecting. Why do I get these entries, and how do I prevent them?
Sample code:
$array1 = array(
"service" => "coding",
"data" => array(
"ITEM" => array(
array(
"CODE" => "9999", //STANDARD
"QUANTITY" => 1
),
)
)
);
$array2 = array(
array(
"a" => "1",
"b" => "1",
"c" => "1",
"d" => "1",
),
array(
"cancel" => "1",
"a" => "1",
"b" => "",
"c" => "",
"d" => "1",
),
array(
"cancel" => "1",
"a" => "",
"b" => "1",
"c" => "1",
"d" => "",
),
);
for ($i = 0; $i < count($array2); $i++) {
foreach ($array2[$i] as $key => $value) {
if($key == 'a' && $value == 1){
array_push($array1['data']['ITEM'],
array('SOMETHING' => 'this_is_a',
'ELSE' => "1"
)
);
}
if($key == 'c' && $value == 1){
array_push($array1['data']['ITEM'],
array('SOMETHING' => 'this_is_c',
'ELSE' => "1"
)
);
}
}
echo "Loop #$i result:\n";
var_export($array1);
echo "\n";
}
You can test the above code as a PHP Sandbox snippet.
The actual result is:
Loop #0 result:
array (
'service' => 'coding',
'data' =>
array (
'ITEM' =>
array (
0 =>
array (
'CODE' => '9999',
'QUANTITY' => 1,
),
1 =>
array (
'SOMETHING' => 'this_is_a',
'ELSE' => '1',
),
2 =>
array (
'SOMETHING' => 'this_is_c',
'ELSE' => '1',
),
),
),
)
Loop #1 result:
array (
'service' => 'coding',
'data' =>
array (
'ITEM' =>
array (
0 =>
array (
'CODE' => '9999',
'QUANTITY' => 1,
),
1 =>
array (
'SOMETHING' => 'this_is_a',
'ELSE' => '1',
),
2 =>
array (
'SOMETHING' => 'this_is_c',
'ELSE' => '1',
),
3 =>
array (
'SOMETHING' => 'this_is_a',
'ELSE' => '1',
),
),
),
)
Loop #2 result:
array (
'service' => 'coding',
'data' =>
array (
'ITEM' =>
array (
0 =>
array (
'CODE' => '9999',
'QUANTITY' => 1,
),
1 =>
array (
'SOMETHING' => 'this_is_a',
'ELSE' => '1',
),
2 =>
array (
'SOMETHING' => 'this_is_c',
'ELSE' => '1',
),
3 =>
array (
'SOMETHING' => 'this_is_a',
'ELSE' => '1',
),
4 =>
array (
'SOMETHING' => 'this_is_c',
'ELSE' => '1',
),
),
),
)
The loop #0 result is correct, but the later loops have additional entries in $array1['data']['ITEM']. Desired result:
Loop #0 result:
array (
'service' => coding
'data' => array (
'ITEM' => array (
0 => array (
'CODE' => 9999
'QUANTITY' => 1
)
1 => array (
'SOMETHING' => 'this_is_a'
'ELSE' => 1
)
2 => array (
'SOMETHING' => 'this_is_c'
'ELSE' => 1
)
)
)
)
Loop #1 result:
array (
'service' => coding
'data' => array (
'ITEM' => array (
0 => array (
'CODE' => 9999
'QUANTITY' => 1
)
1 => array (
'SOMETHING' => 'this_is_a'
'ELSE' => 1
)
)
)
)
Loop #2 result:
array (
'service' => coding
'data' => array (
'ITEM' => array (
0 => array (
'CODE' => 9999
'QUANTITY' => 1
)
1 => array (
'SOMETHING' => 'this_is_c'
'ELSE' => 1
)
)
)
)
You may use array_map to loop through the second array and only push to the first array's ['data']['ITEM'] when the current iteration has a key named a and its value is 1.
$arr1 = [
'service' => 'coding',
'data' => [
'ITEM' => [
[
'CODE' => '9999',
'QUANTITY' => 1
]
]
]
];
$arr2 = [
[
'a' => '1',
'b' => '1',
'c' => '1',
'd' => '1',
],
[
'cancel' => '1',
'a' => '1',
'b' => '',
'c' => '',
'd' => '1',
],
[
'cancel' => '1',
'a' => '',
'b' => '1',
'c' => '1',
'd' => '',
],
];
// loop through the second array ($arr2)
// the "use" is very important here as it let's the callback function to access $arr1 variable
$finalArr = array_map(function ($el) use ($arr1) {
// if in the current iteration a kley named "a" and its value is "1" is found then push it to the first array's ['data']['ITEM'] key.
// $arr1 here is passed by value so the real array won't be channged, we're, more or less, working with copy of $arr1 in the function.
isset($el['a']) && $el['a'] == 1 && ($arr1['data']['ITEM'][] = [
'something' => 'This is a', // tried to keep same output as yours
'else' => $el['a'] // tried to keep same output as yours
]);
// for "c" key
isset($el['c']) && $el['c'] == 1 && ($arr1['data']['ITEM'][] = [
'something' => 'This is c', // tried to keep same output as yours
'else' => $el['c'] // tried to keep same output as yours
]);
// return the $arr1 copy regardless of whether we pushed "a" key or not.
return $arr1;
}, $arr2);
// print the resulting array
print_r($finalArr);
Result (for the sample data):
array(
0 => array(
'service' => 'coding',
'data' => array(
'ITEM' => array(
0 => array(
'CODE' => '9999',
'QUANTITY' => 1,
),
1 => array(
'something' => 'This is a',
'else' => '1',
),
2 => array(
'something' => 'This is c',
'else' => '1',
),
),
),
),
1 => array(
'service' => 'coding',
'data' => array(
'ITEM' => array(
0 => array(
'CODE' => '9999',
'QUANTITY' => 1,
),
1 => array(
'something' => 'This is a',
'else' => '1',
),
),
),
),
2 => array(
'service' => 'coding',
'data' => array(
'ITEM' => array(
0 => array(
'CODE' => '9999',
'QUANTITY' => 1,
),
1 => array(
'something' => 'This is c',
'else' => '1',
),
),
),
),
)
You can learn more about callback functions (anonymous functions) in the PHP manual.
You are not returning $array1['data']['ITEM'] to its original state between each iteration. Just write the following between your for() and your foreach().
$array1['data']['ITEM'] = array_slice($array1['data']['ITEM'], 0, 1);
Because array keys must be unique, you don't need to loop through all elements to see if a or c exists -- this will cost unnecessary cycles.
Futhermore, I find array destructuring to be a good choice to isolate the only two values you seek.
I might recommend this much simpler and more intuitive snippet: (Demo)
foreach ($array2 as $i => ['a' => $a, 'c' => $c]) {
$temp = $array1;
if($a == 1) {
$temp['data']['ITEM'][] = [
'SOMETHING' => 'this_is_a',
'ELSE' => '1'
];
}
if ($c == 1) {
$temp['data']['ITEM'][] = [
'SOMETHING' => 'this_is_c',
'ELSE' => '1'
];
}
echo "Loop #$i result:\n";
var_export($temp);
echo "\n";
}
The unexpected entries are present because $array1 is modified with each iteration (specifically, by array_push). To prevent this, each iteration must operate on a different copy of $array1. Since variable assignment and argument passing will each copy an array, either could be used. Similar to argument passing, closures can inherit (note: not in the OOP sense) variables from outer scopes, binding to their values (which will copy an array), providing a third potential basis for a solution.
The fix requiring the least amount of edits is to assign $array1 to another variable at the start of the loop, and replace $array1 in the rest of the loop with this variable:
for ($i = 0; $i < count($array2); $i++) {
$result = $array1;
// ...
Alternatively, by moving the body of the loop to a function, $array1 becomes a copy within the function body:
function process(array $options, array $output) {
// Ensure entries to test are present:
$options += ['a' => NULL, 'c' => NULL];
/* As an alternative to the above, if entries should be added
* to $output whenever 'a' or 'c' has a truthy value,
* `! empty(...)` could be used instead of the `... == 1`
* tests below.
*/
if ($options['a'] == 1) {
$output['data']['ITEM'][] = [
'SOMETHING' => 'this_is_a',
'ELSE' => 1,
];
}
if ($options['c'] == 1) {
$output['data']['ITEM'][] = [
'SOMETHING' => 'this_is_c',
'ELSE' => 1,
];
}
return $output;
}
foreach ($array2 as $i => $subarray) {
echo "// Loop #$i result:";
var_export( process($subarray, $array1) );
echo ";\n";
}
As a third approach, you could apply array_map to $array2, as is done by ths. For comparison, the preceding foreach loop could be replaced with a call to array_map:
var_export(
array_map(function (array $subarray) use ($array1) {
return process($subarray, $array1);
}, $array2)
);
Or, with an arrow function (which automatically use variables from the outer scope):
var_export(
array_map(
fn (array $subarray) => process($subarray, $array1),
$array2
) );
Note that for arrays that won't be modified (or for which modification won't matter), you can pass them by reference (or bind by reference in closures) to avoid the overhead of copying them.
function process(array &$options, array $output) {
// ...

Replace key in array, with keeping order intact

I would like to replace keys in arrays, because I will move them on two indexes up.
Problem that I am facing is that those are containing same names which will not be ok, if i want to move them up.
This is how array looks like.
$list = array(
'ind' => array(
'messagetype' => 'Alert',
'visibility' => 'Public',
'info' => array(
0 => array(
'urgency' => 'Urgent',
'params' => array(
0 => array(
'Name' => 'display',
'value' => '3; top',
),
1 => array(
'Name' => 'level',
'value' => '1; blue',
),
),
'area' => array(
'ard' => 'Bob',
'code' => array(
0 => array(
'Name' => 'Badge',
'value' => 'GSSD154',
),
),
),
),
1 => array(
'messagetype' => 'Information',
'visibility' => 'Private',
'info' => array(
0 => array(
'urgency' => 'Minor',
'params' => array(
0 => array(
'Name' => 'display',
'value' => '1; left',
),
1 => array(
'Name' => 'level',
'value' => '1; red',
),
),
'area' => array(
'ard' => 'Bob',
'code' => array(
0 => array(
'Name' => 'Badge',
'value' => 'GBECS23',
),
),
),
),
),
),
),
),
);
and this is how I would like the output to be with changing keys in Name0, Name1, which are inside params.
$list = array(
'ind' => array(
'messagetype' => 'Alert',
'visibility' => 'Public',
'info' => array(
0 => array(
'urgency' => 'Urgent',
'params' => array(
0 => array(
'Name0' => 'display',
'value0' => '3; top',
),
1 => array(
'Name1' => 'level',
'value1' => '1; blue',
),
),
'area' => array(
'ard' => 'Bob',
'code' => array(
0 => array(
'Name' => 'Badge',
'value' => 'GSSD154',
),
),
),
),
1 => array(
'messagetype' => 'Information',
'visibility' => 'Private',
'info' => array(
0 => array(
'urgency' => 'Minor',
'params' => array(
0 => array(
'Name0' => 'display',
'value0' => '1; left',
),
1 => array(
'Name1' => 'level',
'value1' => '1; red',
),
),
'area' => array(
'ard' => 'Bob',
'code' => array(
0 => array(
'Name' => 'Badge',
'value' => 'GBECS23',
),
),
),
),
),
),
),
),
);
I have tried with a lots of examples over this website, but could not find one to achieve this.
Code that I used from
How to replace key in multidimensional array and maintain order
function replaceKey($subject, $newKey, $oldKey) {
// if the value is not an array, then you have reached the deepest
// point of the branch, so return the value
if (!is_array($subject)) {
return $subject;
}
$newArray = array(); // empty array to hold copy of subject
foreach ($subject as $key => $value) {
// replace the key with the new key only if it is the old key
$key = ($key === $oldKey) ? $newKey : $key;
// add the value with the recursive call
$newArray[$key] = replaceKey($value, $newKey, $oldKey);
}
return $newArray;
}
$s = replaceKey($list, 'Name0', 'Name');
print "<PRE>";
print_r($s);
at the moment I get this output:
[0] => Array
(
[Name0] => display
[value] => 1; left
)
[1] => Array
(
[Name0] => level
[value] => 1; red
)
any help would be appreciated. regards
A very strange question, but why not?
The following function returns nothing (a procedure) and changes the array in-place using references but feel free to rewrite it as a "real" function (without references and with a return statement somewhere).
The idea consists to search for arrays, with numeric keys and at least 2 items, in which each item has the Name and value keys. In other words, this approach doesn't care about paths where the targets are supposed to be:
function replaceKeys(&$arr) {
foreach ($arr as &$v) {
if ( !is_array($v) )
continue;
$keys = array_keys($v);
if ( count($keys) < 2 ||
$keys !== array_flip($keys) ||
array_keys(array_merge(...$v)) !== ['Name', 'value'] ) {
replaceKeys($v);
continue;
}
foreach ($v as $k => &$item) {
$item = array_combine(["Name$k", "value$k"], $item);
}
}
}
replaceKeys($list);
print_r($list);
demo

Insert Array to Array Collection without looping

I have two array..
Array 1
$arr1 = array(
'task' => 'delete'
)
Array 2
$arr2 = array(
array(
'id' => '1',
'type' => 'post',
),
array(
'id' => '2',
'type' => 'category',
),
array(
'id' => '1',
'type' => 'tag',
),
);
How I insert Array 1 to all Array 2 collection, so the results is.
$arr2 = array(
array(
'id' => '1',
'task' => 'delete',
'type' => 'post',
),
array(
'id' => '2',
'task' => 'delete',
'type' => 'category',
),
array(
'id' => '1',
'task' => 'delete',
'type' => 'tag',
),
);
I can be easily to get the results by using looping, but I want to achieve it not using looping.
Any suggestion ?
Thank you :)
In order to push arraay1 in array2 all indexes, you can use the array_walk with a combination of array merge, you can see below code for instance
<?php
$array1 = array(
'task' => 'delete',
'before' =>'test'
);
$array2=array(
array(
'id' => '1',
'type' => 'post',
),
array(
'id' => '2',
'type' => 'category',
),
array(
'id' => '1',
'type' => 'tag',
),
);
array_walk($array2, function(&$newarray) use ($array1) {
$newarray = array_merge($newarray, $array1);
});
print_r($array2);
?>
array_walk -Apply a user supplied function to every member of an array while array_merge, Merge two arrays into one array
Result
Array (
[0] => Array ( [id] => 1 [type] => post [task] => delete [before] => test )
[1] => Array ( [id] => 2 [type] => category [task] => delete [before] => test )
[2] => Array ( [id] => 1 [type] => tag [task] => delete [before] => test ) )
Git Hub
https://github.com/fahadpatel/insert-array-into-array-without-loop
DEMO
You can use array_walk to skip writing the loop.
$arr1 = array(
'task' => 'delete'
);
$arr2 = array(
array(
'id' => '1',
'type' => 'post',
),
array(
'id' => '2',
'type' => 'category',
),
array(
'id' => '1',
'type' => 'tag',
),
);
array_walk($arr2, function(&$item) use ($arr1) {
$item = array_merge($item, $arr1);
});
You can see the documentation for array_walk here.
You may use array_map. It's looping behind the scenes, though (no real way around it), but at least you don't have to do it yourself:
$arr3 = array_map(static function ($entry) use ($arr1) {
return $entry + $arr1;
}, $arr2);
PHP 7.4 version:
$arr3 = array_map(static fn($entry) => $entry + $arr1, $arr2);
Demo: https://3v4l.org/2u2SR

insert variable in array php foreach

i have a function with a dynamic array.
function doIt($accountid,$targeting){
$post_url= "https://url".$accountid."/";
$fields = array(
'name' => "test",
'status'=> "PAUSED",
'targeting' => array(
$targeting
),
);
$curlreturn=curl($post_url,$fields);
};
And i want to build the array "$fields" dynamically within a foreach loop. Like that:
$accountid="57865";
$targeting=array(
"'device_platforms' => array('desktop'),'interests' => array(array('id' => '435345','name' => 'test')),",
"'device_platforms' => array('mobile'), 'interests' => array(array('id' => '345345','name' => 'test2')),",
);
foreach ($targeting as $i => $value) {
doit($accountid,$value);
}
The Problem is, that the array within the function will not be correctly filled. If i output the array in the function i get something like:
....[0] => array('device_platforms' => array('desktop'),'custom_audiences'=> ['id' => '356346']), )
The beginning [0] should be the problem. Any ideas what im doing wrong?
Hope this will help you out. The problem was the way you are defining $targeting array. You can't have multiple keys with same name
Change 1:
$targeting = array(
array(
'device_platforms' => array('desktop'),
'interests' => array(
array('id' => '435345',
'name' => 'test')),
),
array(
'device_platforms' => array('mobile'),
'interests' => array(
array('id' => '345345',
'name' => 'test2'))
)
);
Change 2:
$fields = array(
'name' => "test",
'status' => "PAUSED",
'targeting' => $targeting //removed array
);
Try this code snippet here this will just print postfields
<?php
ini_set('display_errors', 1);
function doIt($accountid, $targeting)
{
$post_url = "https://url" . $accountid . "/";
$fields = array(
'name' => "test",
'status' => "PAUSED",
'targeting' => $targeting
);
print_r($fields);
}
$accountid = "57865";
$targeting = array(
array(
'device_platforms' => array('desktop'),
'interests' => array(
array('id' => '435345',
'name' => 'test')),
),
array(
'device_platforms' => array('mobile'),
'interests' => array(
array('id' => '345345',
'name' => 'test2'))
)
);
foreach ($targeting as $i => $value)
{
doit($accountid, $value);
}

Accessing multi php array values

Hi I'm trying to access elements in array.
array(
(int) 0 => array(
'requests_users' => array(
'request_id' => '1'
),
(int) 0 => array(
'ct' => '2'
)
),
(int) 1 => array(
'requests_users' => array(
'request_id' => '2'
),
(int) 0 => array(
'ct' => '1'
)
),
(int) 2 => array(
'requests_users' => array(
'request_id' => '4'
),
(int) 0 => array(
'ct' => '2'
)
),
(int) 3 => array(
'requests_users' => array(
'request_id' => '5'
),
(int) 0 => array(
'ct' => '2'
)
)
)
By using for loop (under)
for($row=0;$row<count($list);$row++){
echo $list[$row]['requests_users']['request_id'];
}
I could get request_id values.
However, I'm having a trouble getting a 'ct' values.
Can you guys help me how to print 'ct' values?
how about like this..
for($row=0;$row<count($list);$row++){
echo $list[$row]['requests_users']['request_id'];
echo '<br/>';
echo $list[$row][0]['ct'];
}
try this.
should work
You can get "ct" value :
for($row=0;$row<count($list);$row++){
echo $list[$row][0]['ct'];
}
You can try like below code
for($row=0;$row<count($list);$row++){
echo $list[$row]['requests_users']['request_id'];
echo "<br>";
echo $list[$row][0]['ct'];
echo "<br><br>";
}
To access an elements of above array you can use following recursive function:
public function _convertToString($data){
foreach($data as $key => $value){
if(is_array($value)){
$this->_convertToString($value);
}else{
echo $key .'->'.$value;
}
}
}
you can call above function in following way:
$str = array(
"data" => "check",
"test1" => array(
"data" => "Hello",
"test3" => array(
"data" => "satish"
)
),
"test2" => array(
"data" => "world"
)
);
$this->_convertToString($str);
You can modify output or recursive function to meet your requirements. Can you add original array in your question, I mean not var_dump() so that I can use that directly and modify code in my answer, if needed.

Categories