How to search PHP multidimensional by value and get another values? - php

I have this array:
Array (
[0] => Array ( [cast_id] => 45 [character] => Evelyn Salt [credit_id] => 52fe4555c3a368484e054141 [gender] => 1 [id] => 11701 [name] => Angelina Jolie [order] => 0 [profile_path] => /6tocswK39SrSjZIRDaTpVyPxDz8.jpg )
[1] => Array ( [cast_id] => 3 [character] => Theodore Winter [credit_id] => 52fe4555c3a368484e05409f [gender] => 2 [id] => 23626 [name] => Liev Schreiber [order] => 1 [profile_path] => /qFn3npmqd1qaYOk6yohmi3FbPhc.jpg )
[2] => Array ( [cast_id] => 4 [character] => Darryl Peabody [credit_id] => 52fe4555c3a368484e0540a3 [gender] => 2 [id] => 5294 [name] => Chiwetel Ejiofor [order] => 2 [profile_path] => /fwaEgwYJdzGyBmGcHiH13vobQii.jpg )
[3] => Array ( [cast_id] => 10 [character] => Oleg Vasilyevich Orlov [credit_id] => 52fe4555c3a368484e0540bb [gender] => 2 [id] => 7107 [name] => Daniel Olbrychski [order] => 3 [profile_path] => /nfqJ8xiVNyBQQhnYRkwJzl3iS7s.jpg ))
I need to search for names where gender = 2.
Now I use this code:
function searcharray($value, $gender, $array) {
foreach ($array as $a => $val) {
if ($val[$gender] == $value) {
return $val['name'];
}
}
return null;
}
$iro = searcharray('2', gender, $array);
But it gives me just the first one: Liev Schreiber.
I need all of them separated with ",".

Try like this
function searcharray($value, $gender, $array) {
$arrNames = [];
foreach ($array as $a => $val) {
if ($val[$gender] == $value) {
$arrNames[]= $val['name'];
}
}
return $arrNames;
}

This is because you put a return statement in the middle of a cycle. This way, the first match will terminate the function execution.
For this to work you should first declare an empty results array and push in it every matching value. After every element of the array has been checked and the foreach finishes you can return the imploded array to get all the names separated by comma.
With all this in mind the correct function will be the following:
function searcharray($value, $gender, $array) {
$results = [];
foreach ($array as $a => $val) {
if ($val[$gender] == $value) {
array_push($results, $val['name']);
}
}
return implode(',', $results);
}
$iro = searcharray('2', gender, $array);

Related

Compare values using strpos - PHP

I am trying to return the user_id if value matches with any comma separated value, I am using strpos but I don't why is it not working with 3rd case:
To Compare: (This value is stored in $myArray variable)
Array
(
[0] => cloud
[1] => ai
[2] => test
)
Compare with: (This value is stored in $array_meta_values variable)
Array
(
[0] => Array
(
[tags] => cloud,ai
[user_id] => 1
)
[1] => Array
(
[tags] => cloud,ai,test
[user_id] => 108
)
[2] => Array
(
[tags] => storage,backup,ai
[user_id] => 101
)
)
function searchForId($meta_value, $array)
{
foreach ($array as $key => $val) {
if (strpos($val['tags'], $meta_value)) {
return $val['user_id'];
}
}
}
foreach ($myArray as $usertags) {
$userids[] = searchForId($usertags, $array_meta_values);
}
print_r($userids);
Getting this Output:
Array
(
[1] => 1
[2] => 108
)
It was supposed to add 101 as third element in output array but don't know why it is not working.
Any help appreciated.
Hi so I tried to replicate you question,
$existing = ['cloud', 'ai', 'test'];
$checker = [
array(
"tags" => "cloud,ai",
"user_id" => 1
),
array(
"tags" => "cloud,ai,test",
"user_id" => 108
),
array(
"tags" => "storage,backup,ai",
"user_id" => 101
)
];
function searchForId($meta_value, $array)
{
$ret_array = [];
foreach ($array as $val) {
$et = explode(",", $val['tags']);
if (in_array($meta_value, $et)) {
$ret_array[] = $val['user_id'];
}
}
return $ret_array;
}
foreach ($existing as $usertags) {
$userids[$usertags][] = searchForId($usertags, $checker);
}
echo "<pre>";
print_r($userids);
Is this what you looking for?
Your question is quite unclear, but I'll try with this one:
<?php
$myArray = array('cloud', 'ai', 'test');
$array_meta_values = array(
array(
'tags' => 'cloud,ai',
'user_id' => 1,
),
array(
'tags' => 'cloud,ai,test',
'user_id' => 108,
),
array(
'tags' => 'storage,backup,ai',
'user_id' => 101,
),
);
$userids = [];
foreach ($myArray as $value) {
foreach ($array_meta_values as $array) {
$arrayValues = explode(',', $array['tags']);
if (in_array($value, $arrayValues)) {
$userids[$value][] = $array['user_id'];
}
}
}
echo '<pre>';
print_r($userids);
Output:
Array
(
[cloud] => Array
(
[0] => 1
[1] => 108
)
[ai] => Array
(
[0] => 1
[1] => 108
[2] => 101
)
[test] => Array
(
[0] => 108
)
)

Group array through value

I have an array like this
Array
(
[1] => Array
(
[name] => 123
[id] => 105740727
[email] =>fghfhfh
[phrases_relevant] => 123
[searches_id] => 105740727
)
[2] => Array
(
[name] => porshe
[id] => 105713889
[email] => fghfghf
[phrases_relevant] => porshe
[searches_id] => 105713889
)
[3] => Array
(
[name] => porshe
[id] => 105713889
[email] => fghfghf
[phrases_relevant] => merce
[searches_id] => 105713889
)
I need group this group via value. Output array should looks like below. dimension second and third has same searches_id
[0] => Array
(
[email] => fghfghf
[projects]=>
[porshe] => [porshe, merce]
[1] => ...
edit;
my tried;
foreach ($results as $key => $result) {
$testArray[]['projects'][$result['name']][] = $result['phrases_relevant'];
but this insert one phrases;
You need to sort first by searches_id then apply loop,
function sortByOrder($a, $b)
{
return $a['searches_id'] - $b['searches_id'];
}
usort($myArray, 'sortByOrder');
foreach ($myArray as $key => $value) {
$result[$value['searches_id']]['email'] = $value['email'];
$result[$value['searches_id']]['projects'][] = $value['phrases_relevant'];
}
$result = array_values($result); // reset keys used for array generation
Working demo.
You can use foreach
$res = [];
foreach($arr as $key => $value){
array_key_exists($value['id'], $res) ?
($res[$value['id']]['phrases_relevant'] = $res[$value['id']]['phrases_relevant'].','.$value['phrases_relevant'])
:
($res[$value['id']] = ['email' => $value['email'],'phrases_relevant' => $value['phrases_relevant']]);
}
print_r(array_values($res))
Live Demo

php - Getting Data from multi dimensional array (foreach)

I have a multidimensional array that looks like the one below:
Array
(
[ok] => 1
[result] => Array
(
[0] => Array
(
[update_id] => 1001
[message] => Array
(
[message_id] => 3
[from] => Array
(
[id] => 123
[is_bot] =>
[first_name] => John
[last_name] => Doe
[username] => JohnDoe
[language_code] => de-DE
)
[chat] => Array
(
[id] => 123
[first_name] => John
[last_name] => Doe
[username] => JohnDoe
[type] => private
)
[date] => 1508065616
[text] => Hello
)
)
[1] => Array
(
[update_id] => 1002
[message] => Array
(
[message_id] => 4
[from] => Array
(
[id] => 456
[is_bot] =>
[first_name] => Jane
[language_code] => de-DE
)
[chat] => Array
(
[id] => 456
[first_name] => Jane
[type] => private
)
[date] => 1508067033
[text] => /start
[entities] => Array
(
[0] => Array
(
[offset] => 0
[length] => 6
[type] => bot_command
)
)
)
)
[2] => Array
(
[update_id] => 1003
[message] => Array
(
[message_id] => 5
[from] => Array
(
[id] => 456
[is_bot] =>
[first_name] => Jane
[language_code] => de-DE
)
[chat] => Array
(
[id] => 456
[first_name] => Jane
[type] => private
)
[date] => 1508067035
[text] => Hi
)
)
)
)
I want to get the update_id, the id, the first_name and the text of each of these arrays at the second level (0, 1, 2). Then I want to do something with this variables.
I was searching already in other threads but couldn't get it working right.
<?php
// First I am getting the messages from my Telegram bot
$botToken = "mySecretBotToken"; // removed the token for security reasons here
$website = "https://api.telegram.org/bot".$botToken;
$update = file_get_contents($website."/getUpdates");
$updateArray = json_decode($update, TRUE);
// For testing I was getting here the chatID of the first message
$chatID = $updateArray["result"][0]["message"]["chat"]["id"];
// Please ignore this. Here I was trying around a little bit with foreach
$newArray = array();
$i = 0;
foreach ($updateArray as $key => $value) {
if (is_array($value)) {
$newArray[$i] = array();
foreach ($value as $k => $v) {
$newArray[$i][] = $v;
}
$i++;
}
}
// Printing the chatID for test purposes and replying to the message
print_r($chatID);
file_get_contents($website."/sendmessage?chat_id=".$chatID."&text=test");
?>
Can you please help me?
Similar to the foreach loop you tried:
$newArray = array();
foreach ($updateArray as $key => $value) {
if (is_array($value)) {
foreach ($value as $k => $v) {
$newArray[$k] = array();
$newArray[$k]['update_id'] = $v['update_id'];
$newArray[$k]['id'] = $v['message']['chat']['id'];
$newArray[$k]['first_name'] = $v['message']['chat']['first_name'];
$newArray[$k]['text'] = $v['message']['text'];
}
}
}
Then you can access the chat values using:
foreach ( $newArray as $chat_info ) {
print_r($chat_info['id']);
file_get_contents(
$website."/sendmessage?chat_id=".$chat_info['id']."&text=test"
);
// $chat_info['update_id']
// $chat_info['first_name']
// $chat_info['text']
}
Here's an explanation how YOUR foreach loop works:
$newArray = array();
$i = 0;
foreach ($updateArray as $key => $value) {
// $updateArray keys are ['ok' (not array), 'result' (array)]
if (is_array($value)) { // only 'result' passes this test
$newArray[$i] = array(); // this only happens once
foreach ($value as $k => $v) { // loop over 'result'
// 'result' keys are [0, 1, 2]
$newArray[$i][] = $v;
// $newArray[0][0] = $v (first loop)
// $newArray[0][1] = $v (second loop)
// $newArray[0][2] = $v (third loop)
}
$i++; // this only happens once
}
}
Now you can access your values with:
foreach ( $newArray as $value ) { // only one value in the sample, key: 0
foreach ( $value as $chat_info ) { // 3 values in the sample, keys: 0, 1, 2
print_r($chat_info['message']['chat']['id']);
file_get_contents(
$website."/sendmessage?chat_id=" . $chat_info['message']['chat']['id'] . "&text=test"
);
// $chat_info['update_id']
// $chat_info['message']['chat']['first_name']
// $chat_info['message']['text']
}
}
That shouldn't be to hard...
$output = [];
foreach ($updateArray['result'] as $update) {
$output[] = [
'update_id' => $update['update_id'],
'id' => $update['message']['from']['id'],
'first_name' => $update['message']['from']['first_name'],
'text' => $update['message']['text']
];
}
Not very much to explain here I guess, but feel free to ask if anything is unclear.

Sort a 3 level multi-dimension array by value in PHP

Here is the array,
array(
[0] => Array
(
[IdRedeemProduct] => Item-A
[RedeemOptions] => Array
(
[0] => Array
(
[Points] => 1000
)
[1] => Array
(
[Points] => 2000
)
[2] => Array
(
[Points] => 43000
)
)
[ProductType] => 1
)
[1] => Array
(
[IdRedeemProduct] => Item-B
[RedeemOptions] => Array
(
[0] => Array
(
[Points] => 6200
)
[1] => Array
(
[Points] => 53000
)
)
[ProductType] => 1
)
)
most of the usort examples are just 2 level dimension array. I couldn't find any example for 3 level.
In this case i wanted to sort the smallest points to show first. Item-A will be the first and Item-B will be the 2nd.
foreach ($filteredResults as $key => $row)
{
foreach ($row['RedeemOptions'] as $key2 => $option) {
$vc_array_name[$key] = $option['Points'];
}
}
array_multisort($vc_array_name, SORT_ASC, $filteredResults);
this is working...
Try this:
function sort_2d_desc($array, $key) {
usort($array, function($a, $b) use ($key) {
return strnatcasecmp($b[$key], $a[$key]);
});
return $array;
}
$a = [];
foreach($arr as $key => $val){
$a[$key] = $this->sort_2d_desc($val['RedeemOptions'], 'Points');
}
$newArr = [];
foreach($arr as $key => $val){
$newArr[] = ['IdRedeemProduct' => $val['IdRedeemProduct'], 'RedeemOptions' => $a, 'ProductType' => $val['ProductType']];
}
print_r($newArr);

list and count elements in array php

I have the following array and am trying to loop through it with php, generate a list of the "Type" and count how many. The Type is the key, but there will be unique values such as Call, To-do, Meeting, Proposal, etc. My goal is to have the following out put:
Call 2
To-do 1
Meeting 3
Proposal 4
The above are not the values that will be output from the following array, but I wanted you to have an idea of what I am trying to accomplish. Please help!
Array (
[0] => Array (
[0] => Call
[Type] => Call
[1] => fxxxx#xxxxentllc.com
[EmailAddress] => xxxxr#xxxxentllc.com
[2] => 3xxxx00
[Phone] => 31xxxx00
[3] => 31xxxx871
[MobilePhone] => 31xxxx871
[4] => 102795
[CustomerID] => 102795
[5] => Nortxxxxal
[Company] => Noxxxxal
[6] => Frank
[FirstName] => Frank
[7] => Syxxxxer
[LastName] => Sxxxxter
[8] => 3
[Priority] => 3
[9] => invite to Haxxxxales for lunch
[Details] => invite to Hafxxxxales for lunch
[10] => 4503
[ActivityID] => 4503
[11] => 05/23/13
[DueDate] => 05/23/13
)
[1] => Array (
[0] => To-do
[Type] => To-do
[1] => fsxxxxer#summxxxxntllc.com
[EmailAddress] => fsxxxxer#summixxxxtllc.com
[2] => 315xxxx000
[Phone] => 3154xxxx0
[3] => 315xxxx1
[MobilePhone] => 315xxxx1
[4] => 102795
[CustomerID] => 102795
[5] => Norxxxxl
[Company] => Norxxxxcal
[6] => Frxxxxk
[FirstName] => Fxxxxk
[7] => Sxxxxr
[LastName] => Syxxxxer
[8] => 3
[Priority] => 3
[9] => find out who contact is for xxxxdical center
[Details] => find out who contact is foxxxxcal center
[10] => 4504
[ActivityID] => 4504
[11] => 05/23/13
[DueDate] => 05/23/13
)
)
This should do it:
$type_counts = array_count_values(array_map(function($x) {return $x['Type'];}, $array));
The array_map will return an array containing all the Type elements, then array_count_values will count the number of each of these and return this as an associative array.
something along the lines of:
foreach ($array as $key => $value) {
if (isset($result[$key])) {
$result[$key]++;
} else {
$result[$key] = 1;
}
}
if it is a muldi-dimensional array, just put another for each in there but that should give you an idea
$types = array();
foreach($array as $item) {
isset(${$item['Type']}) ? ${$item['Type']}++ : ${$item['Type']} = 1;
if(!in_array($item['Type'], $types) {
$types[] = $item['Type'];
}
foreach($types as $type) {
echo "$type ${$type}\n";
}
I think you can loop in your array and count each occorrence
$Call = 0;
$To_do = 0;
$Meeting = 0;
$Proposal = 0;
foreach($array as $data)
{
if($data['Type'] == 'Call')
{
$Call++;
} else if($data['Type'] == 'To-do')
{
$To_do++;
} else if($data['Type'] == 'Meeting')
{
$Meeting++;
} else if($data['Type'] == 'Proposal')
{
$Proposal++;
}
}
In this way you will have stored in each variable $Call $To_do $Meeting $Proposal its relative count
you can use (array_count_values($array));
http://php.net/manual/en/function.array-count-values.php
This gives count of all the keys in an array.
If you want only for the specific keys then use foreach loop
The one Petros mentioned is the best way to do it.
I would do something along the lines of:
$your_array = /* Your Array */
$types_count = array();
foreach ($your_array as $type_array){
$types_count[$type_array['Type']]++;
}

Categories