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.
Related
i want to transform this array
Array
(
[0] => Array
(
[text] => i
[age] => 30
[gender] => male
[job] => driver
)
[1] => Array
(
[text] => am
[age] => 30
[gender] => male
[job] => driver
)
[2] => Array
(
[text] => bob
[age] => 30
[gender] => male
[job] => driver
)
)
into this
Array
(
[details] => Array
(
[text] => i am Bob
[age] => 30
[gender] => male
[job] => driver
)
)
i have tried array merge array_merge($array1,$array2); using foreach loop no luck..needless to post here the tried code any idea how to achieve this kind of operations
Just need to loop through and test to see if you've already populated the item - if not, add to is
$details = [];
foreach ($array as $info) {
foreach ($info as $key => $val) {
if (!isset($details[$key])) $details[$key] = $val;
else {
if ($details[$key] != $val) $details[$key].= " " . $val;
}
}
}
Try this
$array = //your array
$array2 = array();
$add = "";
foreach($array as $value) {
$add .= $array ['text'];
$array2['details']['age'] = $value['age'];
$array2['details']['gender'] = $value['gender'];
$array2['details']['job'] = $value['job'];
}
$array2.unshift($add);
print_r($array2);
I have an array like this and it can contain multiple values:
Array
(
[rpiid] => Array
(
[1] => 86
)
[sensor_id] => Array
(
[1] => 1
)
[when] => Array
(
[1] => 2014-02-24
)
[val] => Array
(
[1] => 000
)
[train] => Array
(
[1] => True
)
[valid] => Array
(
[1] => False
)
[button] => update
)
Of course, here there is only the number 1 each time but sometimes I have 0, 1, 2 and a value associated. This is because I get this from a GET from multiple forms.
How can I transform this array into
Array
(
[0] => Array
(
[rpiid] => 86
[sensor_id] => 1
...
Thanks,
John.
if your array is $get
$newArray = Array();
foreach($get as $secondKey => $innerArray){
foreach($value as $topKey => $value) {
$newArray[$topKey][$secondKey] = $value;
}
}
This should work
$new_array = array();
foreach($first_array as $value => $key){
$new_array[$key] = $value[1];
}
Sure you can, take a look at this small example:
$a = [ 'rpid' => [1], 'cpid' => [2,2] ];
$nodes = [];
foreach($a as $node => $array) {
foreach($array as $index => $value) {
if(empty($nodes[$index]))
$nodes[$index] = [];
$nodes[$index][$node] = $value;
}
}
print_r($nodes):
Array
(
[0] => Array
(
[rpid] => 1
[cpid] => 2
)
[1] => Array
(
[cpid] => 2
)
)
how can i count an element if it appears more than once in the same array?
I already tried with array_count_values, but it did not work, is it beacuse i got more than one key and value in my array?
This is my output from my array (restlist)
Array (
[0] => Array ( [restaurant_id] => 47523 [title] => cafe blabla)
[1] => Array ( [restaurant_id] => 32144 [title] => test5)
[2] => Array ( [restaurant_id] => 42154 [title] => blabla2 )
[3] => Array ( [restaurant_id] => 32144 [title] => test5)
[4] => Array ( [restaurant_id] => 42154 [title] => blabla2 )
)
I want it to count how many times the same element appears in my array and then add the counted value to my newly created 'key' called hits in the same array.
Array (
[0] => Array ( [restaurant_id] => 47523 [title] => cafe blabla [hits] => 1)
[1] => Array ( [restaurant_id] => 32144 [title] => test5 [hits] => 2)
[2] => Array ( [restaurant_id] => 42154 [title] => blabla2 [hits] => 2)
)
This is how i tried to do what i wanted.
foreach ($cooltransactions as $key)
{
$tempArrayOverRestaurants[]= $key['restaurant_id'];
}
$wordsRestaruants = array_count_values($tempArrayOverRestaurants);
arsort($wordsRestaruants);
foreach ($wordsRestaruants as $key1 => $value1)
{
$temprestaurantswithhits[] = array(
'restaurant_id' => $key1,
'hits' => $value1);
}
foreach ($restlistas $key)
{
foreach ($temprestaurantswithhits as $key1)
{
if($key['restaurant_id'] === $key1['restaurant_id'])
{
$nyspisestedsliste[] = array(
'restaurant_id' => $key['restaurant_id'],
'title' => $key['title'],
'hits' => $key1['hits']);
}
}
}
I know this is probably a noob way to do what i want but i am still new at php..I hope you can help
Just try with associative array:
$input = array( /* your input data*/ );
$output = array();
foreach ( $input as $item ) {
$id = $item['restaurant_id'];
if ( !isset($output[$id]) ) {
$output[$id] = $item;
$output[$id]['hits'] = 1;
} else {
$output[$id]['hits']++;
}
}
And if you want to reset keys, do:
$outputWithoutKeys = array_values($output);
How to arrange this array by last inner index ( 0, 1, 2 ) and get the value of the last inner index as the value of each second index:
Array
(
[text] => Array
(
[grid] => Array
(
[0] => 3
[1] => 4
[2] => 5
)
[image] => Array
(
[0] =>
[1] =>
[2] =>
)
[align] => Array
(
[0] => left
[1] => right
[2] => left
)
[title] => Array
(
[0] =>
[1] =>
[2] =>
)
[content] => Array
(
[0] =>
[1] =>
[2] =>
)
)
)
And have the results as below:
Array
(
[text] => Array
(
[0] => Array
(
[grid] => 3
[image] =>
[align] => left
[title] =>
[content] =>
)
[1] => Array
(
[grid] => 4
[image] =>
[align] => right
[title] =>
[content] =>
)
[2] => Array
(
[grid] => 5
[image] =>
[align] => left
[title] =>
[content] =>
)
)
)
This will do the work
function restructure($arr){
$newArr = array();
foreach($arr as $k => $v){
foreach($v as $k1 => $v1){
foreach($v1 as $k2 => $v2){
$newArr[$k][$k2][$k1] = $v2;
}
}
}
return $newArr;
}
As SiGanteng suggested, i dont see other ways than a for/foreach loop:
function buildArray($source, $key = false)
{
// Build the new array
$new_array = array();
// Define groups
$groups = $key === false ? array_keys($source) : array($key);
foreach($groups AS $group)
{
// Get the keys
$keys = array_keys($array[$group]);
// Count the values
$num_entries = count($array[$group][$keys[0]]);
for($i = 0; $i < $num_entries; $i++)
{
foreach($keys AS $key)
{
$new_array[$group][$i][$key] = $array[$group][$key][$i];
}
}
}
return $new_array;
}
This allow you to define the key you need to build; If not specified, the function build the array for every key.
This should work.
function formatit($arr) {
$new = array();
foreach($arr as $k=>$v) {
foreach($v as $k1=>$v1) {
$new[$k1][$k] = $v1;
}
}
return $new;
}
Tested. Call it as
$arr['text'] = formatit($arr['text']);
http://ideone.com/rPzuR
Hello I have POST array that looks like this,
Array (
[email_address] => Array (
[0] => simon#simonainley.info
[1] => simon2#simonainley.info
)
[firstname] => Array (
[0] => Simon
[1] => Simon2
)
[surname] => Array (
[0] => Ainley
[1] => Ainley2
)
[companies_company_id] => NULL,
[save_user] => Save User
)
I wanting to create an new array where I would get the first email_address, firstname, and surname into an array, deal with that data and then proceed to the next email-address, firstname and surname.
Is this possible? I have tried this code,
$newArray = array();
foreach($_POST as $key => $value) {
$newArray[] = $value;
}
however that code just produces this,
Array (
[0] => Array (
[0] => simon#simonainley.info
[1] => simon2#simonainley.info
)
[1] => Array (
[0] => Simon
[1] => Simon2
) [2] => Array ( [0] => Ainley [1] => Ainley2 ) [3] => [4] => Save User ) 1
What do I need to do?
$count = count($_POST['firstname']);
$result = array();
for ($i = 0; $i <= $count; $i ++) {
$result[] = array(
'email_address' => $_POST['email_address'][0],
'firstname' => $_POST['firstname'][0],
'lastname' => $_POST['lastname'][0]
);
}
or (if the numeric indices have any meaning)
$result = array();
foreach (array_keys($_POST['email_address']) as $index) {
$result[$index] = array(
'email_address' => $_POST['email_address'][$index],
'firstname' => $_POST['firstname'][$index],
'lastname' => $_POST['lastname'][$index]
);
}
You could try:
foreach($_POST as $key=>$value)
{
$count=0;
foreach($value as $val)
{
$newArray[$count++]=Array($key=>$val);
}
}
You only need to re-order the elements into the $_POST array:
$users = array();
foreach($_POST as $key => $values) {
if (is_array($values)) {
foreach($values as $index => $value) {
$users[$index][$key] = $value;
}
}
}
With the data you provided, it will give you this in the $users array:
[0] => Array
(
[email_address] => simon#simonainley.info
[firstname] => Simon
[surname] => Ainley
)
[1] => Array
(
[email_address] => simon2#simonainley.info
[firstname] => Simon2
[surname] => Ainley2
)
Elements in $_POST that are not an array are ignored and filtered out.