I am trying to get value of is_activated column key. But can not get the exact value. Have tried array_search()
Review the array
Need to check value of all is_activated key whether it's value is 1 or not.
Array
(
[0] => Array
(
[first_name] => Array
(
[0] => john
)
[is_activated] => Array
(
[0] => 0
)
)
[1] => Array
(
[first_name] => Array
(
[0] => mark
)
[is_activated] => Array
(
[0] => 1
)
)
[2] => Array
(
[first_name] => Array
(
[0] => pretik
)
[is_activated] => Array
(
[0] => 0
)
)
)
I have tried this below solution but can can not get result.
$is_user_activated = array_search(1,array_column($activity,'is_activated'));
if($is_user_activated == 1) { echo 'yes'; }
else { echo 'no'; }
I think you want to be doing this in a loop rather than using array_search. Use a foreach() to get your desired result:
foreach($yourArray as $item) {
if($item['is_activated'][0] == 1) {
echo 'yes';
} else {
echo 'no';
}
}
You can use the array_filter() for such tasks, it allows to use a callback filter function:
<?php
$data = [
[
'first_name' => ['john'] ,
'is_activated' => [0]
],
[
'first_name' => ['mark'],
'is_activated' => [1]
],
[
'first_name' => ['pretik'],
'is_activated' => [0]
]
];
$matches = array_filter($data, function($entry) {
return in_array(1, $entry['is_activated']);
});
var_dump($matches);
The output of that is:
array(1) {
[1]=>
array(2) {
["first_name"]=>
array(1) {
[0]=>
string(4) "mark"
}
["is_activated"]=>
array(1) {
[0]=>
int(1)
}
}
}
Reason why that is a bit awkward is that your initial data has a very strange structure: the values of the elements are arrays themselves holding the actual values instead of scalar values themselves. That makes searching more complex than in "normal" situations. So take a good look if maybe you can fix that strange structure instead to be able to use an easier search approach.
You can get the activated users via array_filter:
$activated = array_filter($users, function($record) {
return reset($record['is_activated']) == 1;
});
This will only keep users who are activated, you can then simply count the array to see if you have any activated users:
echo count($activated) ? 'yes' : 'no';
Example here: http://ideone.com/mMuJcO
Related
I have the following array
Array
(
[tags] => Array
(
[0] => hello
)
[assignee] => 60b6a8a38cf91900695dd46b
[multiple_assignee] => Array
(
[0] => Array
(
[accountId] => 60b6a8a38cf91900695dd46b
)
[1] => Array
(
[accountId] => 5b39d23d32e26a2de15f174f
)
)
)
I want to remove 60b6a8a38cf91900695dd46b from the multiple_assignee array.
I have tried with the following code:
if (($key = array_search($this->getUsersHashMapValue($responsiblePartyIds[0]), $mutipleAssignee)) !== false) {
unset($mutipleAssignee[$key]['accountId']);
}
But it is not removing that element. The intention is I don't want to repeat the 60b6a8a38cf91900695dd46b assignee in the multiple assignee array.
I have also tried with the following code:
foreach($mutipleAssignee as $subKey => $subArray){
if($subArray['accountId'] == $this->getUsersHashMapValue($responsiblePartyIds[0])){
unset($mutipleAssignee[$subKey]);
}
}
But it is resulting as
Array
(
[tags] => Array
(
[0] => hello
)
[assignee] => 60b6a8a38cf91900695dd46b
[multiple_assignee] => Array
(
[1] => Array
(
[accountId] => 5b39d23d32e26a2de15f174f
)
)
)
rather than
[multiple_assignee] => Array
(
[0] => Array
(
[accountId] => 5b39d23d32e26a2de15f174f
)
)
Thank you
Just extract the accountId column and search that. Then use that key:
$key = array_search($this->getUsersHashMapValue($responsiblePartyIds[0]),
array_column($mutipleAssignee, 'accountId'));
unset($mutipleAssignee[$key]);
After your edit it seems you just want to reindex the subarray after unset:
$mutipleAssignee = array_values($mutipleAssignee);
I would just use a simple for loop. All of the array_* functions are really helpful but I find that they hide nuances. Since I don't have your functions I'm just making a plain-old one, but you should be able to port this.
$data = [
'tags' => [
'hello',
],
'assignee' => '60b6a8a38cf91900695dd46b',
'multiple_assignee' => [
[
'accountId' => '60b6a8a38cf91900695dd46b',
],
[
'accountId' => '5b39d23d32e26a2de15f174f',
],
],
];
$assignee = $data['assignee'];
foreach ($data['multiple_assignee'] as $multiple_assignee_key => $multiple_assignee) {
// if the root assignee is also listed in the multiple assignee area
if ($multiple_assignee['accountId'] === $assignee) {
// remove the duplicate from the multiple area
unset($data['multiple_assignee'][$multiple_assignee_key]);
// re-index the array
$data['multiple_assignee'] = array_values($data['multiple_assignee']);
}
}
This outputs:
array(3) {
["tags"]=>
array(1) {
[0]=>
string(5) "hello"
}
["assignee"]=>
string(24) "60b6a8a38cf91900695dd46b"
["multiple_assignee"]=>
array(1) {
[0]=>
array(1) {
["accountId"]=>
string(24) "5b39d23d32e26a2de15f174f"
}
}
}
Demo here: https://3v4l.org/tYppK
Hi to all I have those nested json data, at a very basic level they looks like this
$json = '{
"destinazione": [
{
"corfu": [
{
"dataPartenza": [
{
"18/11/83": [
{
"sistemazione": [
{
"comfort": [
[
{
"2pax-studio": "€6"
}
]
]
}
]
}
]
}
]
}
]
}
]
}';
Now I want to send those datas to the php server for manipulation stuffs, and I'm using this code to show the data
$jsonDecode = json_decode($json,TRUE);
print_r($jsonDecode);
And I'm Obtaining this:
Array
(
[destinazione] => Array
(
[0] => Array
(
[corfu] => Array
(
[0] => Array
(
[dataPartenza] => Array
(
[0] => Array
(
[18/11/83] => Array
(
[0] => Array
(
[sistemazione] => Array
(
[0] => Array
(
[comfort] => Array
(
[0] => Array
(
[0] => Array
(
[2pax-studio] => €6
)
)
)
)
)
)
)
)
)
)
)
)
)
)
But I'm expecting something similar to this,
Array
(
[destinazione] => Array
(
[corfu] => Array
(
[dataPartenza] => Array
(
[18/11/83] => Array
(
[sistemazione] => Array
(
[comfort] => Array
(
[2posti] => 6euro
)
)
)
)
)
)
)
so I was expecting an associative array without 0 => at top of each level, maybe my json scheme is wrong and this is why I'm obtaining an unexpected result? I'm noob with php..
many thanks
Ideally you would want to solve this problem at the source, as in fixing the thing that's producing this weird format.
Failing that, if you need to perform operations on data structures of arbitrary depth that's a case for recursion.
$data = json_decode($json, true);
function ensmallen($input) {
if( is_array($input) ) {
// if it's a numerically-indexed array with exactly one key
if( array_keys($input) === [0] ) {
return ensmallen($input[0]);
} else {
foreach($input as $key => $value) {
$input[$key] = ensmallen($value);
}
}
}
return $input;
}
var_dump(ensmallen($data));
Output:
array(1) {
["destinazione"]=>
array(1) {
["corfu"]=>
array(1) {
["dataPartenza"]=>
array(1) {
["18/11/83"]=>
array(1) {
["sistemazione"]=>
array(1) {
["comfort"]=>
array(1) {
["2pax-studio"]=>
string(4) "€6"
}
}
}
}
}
}
}
Beware, though. If any of those indexed arrays ever have more than one entry, eg: more than one destination, this is going to break all the code that comes after it. Since it will be $foo[1]['destinazione'] instead of $foo['destinazione'].
Once again, solving the problem at the source of the data would be the best course of action. The second-best being using the data as-is, and the code I've just posted being a distant third.
There are 2 set of code and each gives 2 different array
First set is this
$this->db->select('id');
$query = $this->db->get('user');
echo "<pre>";
print_r( $query->result());
echo "</pre>";
And gives the following result
Array
(
[0] => stdClass Object
(
[id] => 1
)
[1] => stdClass Object
(
[id] => 2
)
)
Second one is this
$this->db->select('user_id');
$query_two = $this->db->get('request_user');
echo "<pre>";
print_r( $query_two->result());
echo "</pre>";
And gives the following result
Array
(
[0] => stdClass Object
(
[user_id] => 1
)
)
I wish to get final array that should not have the duplicate values, eg in the above 2 array 1 is common in both the array so it should not be there and in resulting array i should get only value 2
You could take the following approach. Make a list of ids from your second array. And then use that list to filter the first. If an id is not in that list: keep it.
<?php
$one = [
(object) ['id' => 1],
(object) ['id' => 2],
];
$two = [
(object) ['id' => 1],
];
$ids_in_two = [];
foreach($two as $val) {
$ids_in_two[] = $val->id;
}
$filtered = array_filter($one, function($val) use ($ids_in_two) {
return !in_array($val->id, $ids_in_two);
});
var_dump($filtered);
Output:
array(1) {
[0]=>
object(stdClass)#1 (1) {
["id"]=>
int(2)
}
}
I have two arrays- one single and other multi-dimensional.
$abc='["first","second","third","fourth"]';
$def='[{"post_id":"1","postid":"42","tags":["eminem","baby","jordan"]},{"post_id":"3","postid":"38","tags"
:["abc","def","jordan"]},{"post_id":"4","postid":"40","tags":["eminem","baby","first","second","fourth"
]}]';
$ghi=json_decode($def,true);
$jkl=json_decode($abc,true);
echo '<pre>';
print_r($jkl);
echo '</pre>';
echo '<pre>';
print_r($ghi);
echo '</pre>';
And this is what it looks like:
Array
(
[0] => first
[1] => second
[2] => third
[3] => fourth
)
Array
(
[0] => Array
(
[post_id] => 1
[postid] => 42
[tags] => Array
(
[0] => eminem
[1] => baby
[2] => jordan
)
)
[1] => Array
(
[post_id] => 3
[postid] => 38
[tags] => Array
(
[0] => abc
[1] => def
[2] => jordan
)
)
[2] => Array
(
[post_id] => 4
[postid] => 40
[tags] => Array
(
[0] => eminem
[1] => baby
[2] => first
[3] => second
[4] => fourth
)
)
)
What I am trying to do is search for the elements of single-dimensional array inside the sub-array tags present in the multi-dimensional array.
This is my code:
$users = array_unique($jkl);
$array = [];
$i=0;
foreach($users as $user)
{
if (in_array($user, $ghi[$i]['tags']))
{
$newdata = array (
'postId' => $ghi[$i]['postid'],
'tag' => $user
);
array_push($array, $newdata);
}
$i++;
}
But I get the error mentioned as the question title.
What could be the possible reason? Thanks!
You have to iterate through multi-dimensional array and do what you want:-
<?php
$abc='["first","second","third","fourth"]';
$def='[{"post_id":"1","postid":"42","tags":["eminem","baby","jordan"]},{"post_id":"3","postid":"38","tags"
:["abc","def","jordan"]},{"post_id":"4","postid":"40","tags":["eminem","baby","first","second","fourth"
]}]';
$ghi=json_decode($def,true);
$jkl=json_decode($abc,true);
$users = array_unique($jkl);
$array = []; // empty array
foreach($ghi as $gh) // iterate through multi-dimensional array not single one
{
for($i=0;$i<count($users);$i++){ // a for loop to iterate through single-dimensional completly
if (in_array($users[$i],$gh['tags'])) // if single dimensional array value exist in multi-dimensional tags array
{
$newdata = array (
'postId' => $gh['postid'],
'tag' => $users[$i]
);
array_push($array, $newdata); // push the data
}
}
}
echo "<pre/>";print_r($array); // print newly created array
?>
Output:-https://eval.in/602523
Note:- Try to put variable name in such a way that they don't produce ambiguity.Thanks
Your both array has different numbers of elements. first array has four elements while second array has three elements. that's why you are getting problem.
You should check variable is set and must be an array. Use !empty() and is_array()
foreach($users as $k=>$user){
if(!empty($ghi[$k]['tags']) && is_array($ghi[$k]['tags'])) { // check this condition here
if (in_array($user, $ghi[$k]['tags'])){
$newdata = array (
'postId' => $ghi[$k]['postid'],
'tag' => $user
);
array_push($array, $newdata);
}
}
}
Note:- I have used array key as $k instead of $i
This is because length of your 2 arrays are different, use isset() to remove error:
as 3rd index of your $ghi array does not exist, and its trying to fetch $ghi[3]['tags'] - that's why error is occurring
Try:
foreach($users as $user)
{
if(isset($ghi[$i]['tags'])) { // just add this condition here
if (in_array($user, $ghi[$i]['tags']))
{
$newdata = array (
'postId' => $ghi[$i]['postid'],
'tag' => $user
);
array_push($array, $newdata);
}
}
$i++;
}
It depends on what you are searching for.
If you want to examine ALL of the $users against ALL of the $ghi array then you need to loop over both each time.
foreach($users as $user)
{
for ($i = 0; $i < count($ghi); $i++) {
if (in_array($user, $ghi[$i]['tags']))
{
$newdata = array (
'postId' => $ghi[$i]['postid'],
'tag' => $user
);
array_push($array, $newdata);
}
}
}
This will result in the $newdata consisting of the following
array(2) { ["postId"]=> string(2) "40" ["tag"]=> string(6) "fourth" }
But if you only want to examine the each array against the other once. Then you need to check to make sure you're not going out of bounds.
$ghi only has 3 elements in it.
there are 4 elements in $users.
So you can either loop through the smaller array in your foreach - switch $users -> $ghi
or check inside the foreach loop that $ghi has a valid element at whatever $i is.
D.
I'm having few arrays as follows. Actually I'm having too many such arrays but for your reference I've printed only few of them:
Array
(
[0] => lineItemData
[1] => name
)
Array
(
[0] => lineItemData
[1] => startDate
)
Array
(
[0] => lineItemData
[1] => endDate
)
Array
(
[0] => lineItemData
[1] => frequencyCapping
[2] => interval
)
Array
(
[0] => lineItemData
[1] => frequencyCapping
[2] => amount
)
Array
(
[0] => orderId
)
Array
(
[0] => isExternal
)
Now you can observe in man of the above arrays key value [lineItemData] is common and it is present at oth index. Now I want to create a new array where the key would be [lineItemData] and other arrays which don't have a value [lineItemData] present within themselves should be new keys and other keys should be keys under every key. My question may confuse you. So I'm printing below the desired output array
Array
(
[lineItemData] => Array
(
[name] =>
[startDate] =>
[endDate] =>
[frequencyCapping] => Array
(
[interval] =>
[amount] =>
)
)
[orderId] =>
[isExternal] =>
)
You can do this with:
$data = [
['lineItemData', 'name'],
['lineItemData', 'startDate'],
['lineItemData', 'endDate'],
['lineItemData', 'frequencyCapping', 'interval'],
['lineItemData', 'frequencyCapping', 'amount'],
['orderId'],
['isExternal']
];
$result = [];
$pointer = &$result;
foreach($data as $keys)
{
foreach($keys as $key)
{
if(is_array($pointer) && !array_key_exists($key, $pointer))
{
$pointer[$key] = null;
}
$pointer = &$pointer[$key];
}
$pointer = &$result;
}
End result will look like:
array(3) {
["lineItemData"]=>
array(4) {
["name"]=>
NULL
["startDate"]=>
NULL
["endDate"]=>
NULL
["frequencyCapping"]=>
array(2) {
["interval"]=>
NULL
["amount"]=>
NULL
}
}
["orderId"]=>
NULL
["isExternal"]=>
NULL
}
Maybe like so?
<?php
$super['lineItemData']['name'] = NULL;
$super['lineItemData']['startDate'] = NULL;
$super['lineItemData']['endDate'] = NULL;
$super['lineItemData']['frequencyCapping']['interval'] = NULL;
$super['lineItemData']['frequencyCapping']['amount'] = NULL;
$super['orderId'] = NULL;
$super['isExternal'] = NULL; ?>
I'm sure someone will get crafty and find a way to make this happen in one array statement. I like this because it's easier for me to manage.