PHP array - create an array from an array? - php

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.

Related

PHP associative array- matched key value of each array will be a table row

I have an array like this-
Array
(
[sku] => Array
(
[0] => SKU125
[1] => SKU121
[2] => SKU122
[3] => SKU124
)
[variation_description] => Array
(
[0] => test another
[1] => test
[2] => test
[3] => test
)
[price_html] => Array
(
[0] => 400,200
[1] => 500
[2] => 600,300
[3] => 700
)
)
Is it possible to covert the array to like this table-
Any kind of help will be appreciated.
Thanks In Advance
As every key (sku , price_html etc) has same amount of data , so just push the corresponding key data to a new array.
$data = [
'sku' => ['SKU125', 'SKU121', 'SKU122', 'SKU124'],
'variation_description' => ['test another', 'test', 'test', 'test'],
'price_html' => ['400,200', '500', '600,300', '700']
];
$re_structured = [];
foreach ($data as $each_key_data ) {
foreach ($each_key_data as $key => $value2 ) {
$re_structured[$key][] = $value2;
}
}
var_dump($re_structured);
You can simply iterate through data and create a new array.
$data = [
'sku' => ['SKU125', 'SKU121', 'SKU122', 'SKU124'],
'variation_description' => ['test another', 'test', 'test', 'test'],
'price_html' => ['400,200', '500', '600,300', '700']
];
$mapped = [];
$keys = array_keys($data);
$rows = count($data[reset($keys)]);
for ($i = 0; $i < $rows; $i++) {
$row = [];
foreach ($keys as $key)
$row[] = $data[$key][$i];
$mapped[] = $row;
}
This will result in
print_r($mapped);
Array
(
[0] => Array
(
[0] => SKU125
[1] => test another
[2] => 400,200
)
[1] => Array
(
[0] => SKU121
[1] => test
[2] => 500
)
[2] => Array
(
[0] => SKU122
[1] => test
[2] => 600,300
)
[3] => Array
(
[0] => SKU124
[1] => test
[2] => 700
)
)

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

Change value inside an array

I'd like to change the values of an array.
Currently my array looks like this:
Array
(
[0] => Array
(
[0] => 12-Multi_select-customfield-retina-ready+Yes
[1] => 12-Multi_select-customfield-retina-ready+N/A
[2] => 12-Multi_select-customfield-retina-ready+No
)
)
I want to remove everything before the + symbol, so in the end the new array will looke like this
Array
(
[0] => Array
(
[0] => Yes
[1] => N/A
[2] => No
)
)
This is my code:
$new_array = array();
foreach( $array as $key => $value ) {
$split = explode("+", $value[0]);
$new_array[] = $split[1];
}
Hoping that it would worked, but when I check the new array, it only shows one value.
Array
(
[0] => Yes
)
Any help in putting me in the right direction is much appreciated.
Please, check it:
<?php
$array[0][0] = '12-Multi_select-customfield-retina-ready+Yes';
$array[0][1] = '12-Multi_select-customfield-retina-ready+N/A';
$array[0][2] = '112-Multi_select-customfield-retina-ready+No';
echo '<pre>';
print_r($array);
$new_array = array();
foreach( $array[0] as $key => $value ) {
$split = explode("+", $value);
$new_array[] = $split[1];
}
print_r($new_array);
echo '</pre>';
Try This this work even if you have multiple key in the original array $original_array[0], $original_array[1] ... :
$original_array[0] = [
0 => '12-Multi_select-customfield-retina-ready+Yes',
1 => '12-Multi_select-customfield-retina-ready+N/A',
2 => '12-Multi_select-customfield-retina-ready+No'
];
print_r($original_array);
$new_array = [];
foreach ($original_array as $key => $value) {
foreach ($value as $index => $val) {
$split = explode("+", $val);
$new_array[$key][] = $split[1];
}
}
print_r($new_array);
Example :
Original array
Array
(
[0] => Array
(
[0] => 12-Multi_select-customfield-retina-ready+Yes
[1] => 12-Multi_select-customfield-retina-ready+N/A
[2] => 12-Multi_select-customfield-retina-ready+No
),
[1] => Array
(
[0] => 12-Multi_select-customfield-retina-ready+Yes
[1] => 12-Multi_select-customfield-retina-ready+N/A
[2] => 12-Multi_select-customfield-retina-ready+No
)
)
New Array
Array
(
[0] => Array
(
[0] => Yes
[1] => N/A
[2] => No
),
[1] => Array
(
[0] => Yes
[1] => N/A
[2] => No
)
)

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.

how to get array from get to normal array in php

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
)
)

Categories