how to merge same key in an array in php - php

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

Related

Find Unique Value from a array

I have a Multidimensional array, I need to find if array have same value of 'brand' attribute then return its id.
I tried via some array functions but it didn't work.
What I Tried:
1)
$backwards = array_reverse($attribute);
echo '<pre>';
$last_item = NULL;
$i = 0;
foreach ($backwards as $current_item) {
if ($last_item === $current_item[$i]['value']) {
echo '<pre>'; print_r($current_item[$i]['value']);
}
$last_item = $current_item[$i]['value'];
echo '<pre>'; print_r($last_item);
$i++;
}
2)
$j = 1;
$i = 0;
foreach ($attributeValues as $attributeData) {
foreach ($attribute as $value) {
if($value[$i]['value'] == $value[$j]['value']) {
echo '<pre>'; print_r($value); die();
}
$j++;
}
}
All my solution's not worked, please help.
[0] => Array
(
[0] => Array
(
[name] => brand
[value] => 54
[id] => 5251
[price] => 15000.0000
)
[1] => Array
(
[name] => model
[value] => 1200
[id] => 5251
[price] => 15000.0000
)
)
[1] => Array
(
[0] => Array
(
[name] => brand
[value] => 54
[id] => 5250
[price] => 15000.0000
)
[1] => Array
(
[name] => model
[value] => 1200
[id] => 5250
[price] => 12000.0000
)
)
[2] => Array
(
[0] => Array
(
[name] => brand
[value] => 89
[id] => 518
[price] => 100.0000
)
[1] => Array
(
[name] => model
[value] => 12
[id] => 518
[price] => 100
)
)
If [name]=>brand and [name]=>model value's of first array is same as second array's value then return [id].
You need two for loop.
$result =[];
foreach ($arr as $key => $value) {
foreach($value as $v){
$result[$v['name']][] = $v['id'];
}
}
$result = array_map("array_unique", $result); // to make it unique
print_r($result);
// if you want to check ids for brand
//print_r($result['brand']);
Output:
Array
(
[brand] => Array
(
[0] => 5251
[1] => 5250
[3] => 518
)
[model] => Array
(
[0] => 5251
[1] => 518
)
)
Demo.
EDIT
Then you can group it by name and value of it
$result =[];
foreach ($arr as $key => $value) {
foreach($value as $v){
$result[$v['name']."|".$v['value']][] = $v['id'];
}
}
$result = array_map("array_unique", $result);
print_r($result);die;
Demo.
you can use foreach and iterate through the array
$res = [];
foreach($arr as $k => $v){
if($v[0]['name'] == $v[1]['name'])
$res[$v[0]['name']] = $v[0]['id'];
}
If you want to match the index value try this
foreach($arr as $k => $v){
if($v[0]['value'] == $v[1]['value'])
$res[] = $v[0]['id'];
}
Working example

How can I access multi-dimensional array with php?

My array is like this. So how can I access the names,values with php?
Array(
[0] => Array
(
[name] => subject
[value] => คอมพิวเตอร์ ม.3
)
[1] => Array
(
[name] => subject_code
[value] => ง33101
)
[2] => Array
(
[name] => subject_hour
[value] => 2
)
[3] => Array
(
[name] => semester
[value] => 1
)
[4] => Array
(
[name] => level
[value] => 3
)
[5] => Array
(
[name] => classroom
[value] => 301
)
[6] => Array
(
[name] => classroom
[value] => 302
)
)
I have tried FOREACH to loop through the array and it does the job, but how can I get their names and values to be used later?
My FOREACH code:
foreach($objects AS $values){
foreach($values as $value){
echo $value.'<br/>';
}
}
assume your array is $array:
foreach($array as $item){
$name = $item['name']; //extract name
$value = $item['value']; //extract value
echo $name.' '.$value.'</br>';
}
To get the index/key, just name it:
foreach($collection as $key => $value)
print($key . ' = ' . $value . '\n');
Iteration over $objects to get values and names;
foreach($objects as $value){
echo "Name: ".$value['name'];
echo " - Value: ".$value['value'];
echo "<br/>";
}

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.

Using PHP to transform a 3D array into a 2D one

My form produces a 3 dimensional array. I would like to transform this array into a 2 dimensional one.
I tried this with no success:
$_rows = array();
foreach ($_contacts as $name => $_arr) {
foreach ($_arr as $key => $val) {
$_rows[] = array ($name => $val);
}
}
Data Source:
[_contacts] => Array
(
[name] => Array
(
[0] => foo
[1] => bar
)
[phone] => Array
(
[0] => 012345
[1] => 098765
)
[email] => Array
(
[0] => mail.com
[1] => yahoo.com
)
)
Desired output:
Array
(
[0] => Array
(
[name] => foo
[phone] => 012345
[email] => mail.com
)
[1] => Array
(
[name] => bar
[phone] => 098765
[email] => yahoo.com
)
)
Any thoughts were I went wrong?
$_rows = array();
foreach ($_contacts as $name => $_arr) {
foreach ($_arr as $key => $val) {
$_rows[$key][$name] = $val;
}
}

PHP array - create an array from an array?

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.

Categories