insert 2 array value to new array with new key - php

i have below two array :
Array 1
(
[0] => Daughter
[1] => Daughter
[2] => Son
)
Array 2
(
[0] => Nitu
[1] => ritu
[2] => ramesh
)
and i want different array for each key as below :
Array(
"relation" => Daughter
"name" => Nitu
)
Array(
"relation" => Daughter
"name" => ritu
)
Array(
"relation" => Son
"name" => ramesh
)
above array 1 & array 2 can be long as per user input. so i want to insert value to new array in loop dynamically.

You simply need to loop through your array and store it in a variable $result.
Try this:
$array1 = array('Daughter', 'Daughter','Son');
$array2 = array('Nitu', 'Ritu', 'Ramesh');
foreach ($array1 as $k => $arr1) {
$result[] = array(
'relation' => $arr1,
'name' => $array2[$k]
);
}

try this,
$Aarray1 = Array
(
"0" => "Daughter",
"1" => "Daughter",
"2" => "Son"
);
$Aarray2 = Array
(
"0" => "Nitu",
"1" => "ritu",
"2" => "ramesh"
);
foreach($Aarray1 as $key=>$val)
{
$new_array[$key]["relation"] = $val;
$new_array[$key]["name"] = $Aarray2[$key];
}
DEMO

Try this :
$arrayFirst = Array("0" => "Daughter", "1" => "Daughter", "2" => "Son");
$arraySecond = Array("0" => "Nitu","1" => "ritu","2" => "ramesh");
foreach($arrayFirst as $key=>$value)
{
$new_array[$key]["relation"] = $value;
$new_array[$key]["name"] = $arraySecond[$key];
}

Probably you are trying to search for array_combine
You can check the documentation here

Related

PHP: Modify an associative array based on value of a key

I have an array like this
Array
(
[id] => 3
[type] => default
[place] => 1
)
Array
(
[id] => 3
[type] => default
[place] => 2
)
Array
(
[id] => 3
[type] => default
[place] => 3
)
This array is created from this php
for($count=1;$count <= 3;$count++){
$places_array = array(
"id" => "3",
"type" => "default",
"place" => $count,
);
}
Now I want to change the result of this array if the place is found by the php mysql data. For example I have this array.
Array
(
[id] => 7
[type] => 1
[place] => 2
[description] => This is item place 2
[image] => this_is_the_image.png
)
As you can see that the second array is in "place 2". Now I want the result be like this
Array
(
[id] => 3
[type] => default
[place] => 1
)
Array
(
[id] => 7
[type] => 1
[place] => 2
[description] => This is item place 2
[image] => this_is_the_image.png
)
Array
(
[id] => 3
[type] => default
[place] => 3
)
How to achieve this? I have already done with array_search function but no luck.
anyone please help me
=======================EDIT FULL CODE================================
Here is the code, I'm showing the data from database and call it in while loop function
for($count=1;$count <= $max_places;$count++){
$array[] = array(
"id" => $res['id'],
"type" => "default",
"place" => $count
);
while($arr = $stmts->fetch()){
$key = array_search($arr['place'], array_column($array, 'place'));
if($key && array_key_exists($key, $array)) {
$array[$key] = [
"id" => $arr['id'],
"type" => $arr['type'],
"place" => $arr['place'],
"url" => $arr['url'],
"image" => $arr['image']
];
}
}
}
=========================SWAPPED CODE==============================
while($arr = $stmts->fetch()){
$array[] = [
"id" => $arr['id'],
"type" => $arr['type'],
"place" => $arr['place'],
"url" => $arr['url'],
"image" => $arr['image']
];
for($count=1;$count <= $max_places;$count++){
$key = array_search($arr['place'], array_column($array, 'place'));
if($key && array_key_exists($key, $array)) {
$array[] = array(
"id" => $res['id'],
"type" => "default",
"place" => $count
);
}
}
}
You can use the built in
array_multisort()
function.
Example copied from php.net
A nice way to do sorting of a key on a multi-dimensional array without having to know what keys you have in the array first:
<?php
$people = array(
array("name"=>"Bob","age"=>8,"colour"=>"red"),
array("name"=>"Greg","age"=>12,"colour"=>"blue"),
array("name"=>"Andy","age"=>5,"colour"=>"purple")
);
var_dump($people);
$sortArray = array();
foreach($people as $person){
foreach($person as $key=>$value){
if(!isset($sortArray[$key])){
$sortArray[$key] = array();
}
$sortArray[$key][] = $value;
}
}
$orderby = "name"; //change this to whatever key you want from the array
array_multisort($sortArray[$orderby],SORT_DESC,$people);
var_dump($people);
?>
There's no checking on whether your array keys exist, or the array data you are searching on is actually there, but easy enough to add.
Check out https://www.php.net/manual/de/function.ksort.php (user contributes) and
https://www.php.net/manual/de/function.array-multisort.php
Use array_column() with array_search() to get the array key that needs to be modified. See the following code snippet:
<?php
// Here is trick; get the key of the array using array_column
$key = array_search('2', array_column($array, 'place'));
// If any key found modify the array
if ($key && array_key_exists($key, $array)) {
$array[$key] = [
'id' => 7,
'type' => 1,
'place' => 2,
'description' => 'This is item place 2',
'image' => 'this_is_the_image.png',
];
}
print_r($array);
See the demo
Try :
for($count=1;$count <= 3;$count++){
if(array_search($count,array_column("place",$array_from_db)) continue;
$places_array = array(
"id" => "3",
"type" => "default",
"place" => $count,
);
}
This will skip:
Array
(
[id] => 3
[type] => default
[place] => 2
)
=========== EDIT =============
while($arr = $stmts->fetch())
{
$array[$arr['place']] = [
"id" => $arr['id'],
"type" => $arr['type'],
"place" => $arr['place'],
"url" => $arr['url'],
"image" => $arr['image']
];
}
for($count=1;$count <= $max_places;$count++){
if(!isset($array[$count])){
$array[$count] = array(
"id" => $res['id'],
"type" => "default",
"place" => $count
);
}
}
ksort($array);
Found the answer, thanks for all help.
Here is the trick
first we need to determine the main array like this
for($count=1;$count <= $max_places;$count++){
$array[$count] = array(
"id" => $res['id'],
"type" => "default",
"place" => $count
);
}
Then we need to find which place is not available and show the matches.
while($arr = $stmts->fetch()){
$key = array_search($arr['place'], array_column($array, 'place'));
$key+=1;
if($key && array_key_exists($key, $array)) {
$array[$arr['place']] = [
"id" => $arr['id'],
"type" => $res['type'],
"place" => $arr['place'],
"url" => $arr['url'],
"image" => $arr['image']
];
}
}
The trick is in the
$key+=1;
Because the default key in array is 0.
Hope this can help others

shift multidimentional array to single array

I want to remove key 0 from parent array and set child array as parent.
Here I will get single value so one array is ok for me.
My current array looks like this
Array
(
[0] => Array
(
[id] => 3
[api_key] => acount266
[auth_domain] => Tester26
[database_url] => vcc.test.acc+27#gmail.com
[project_id] => 12345
[storage_bucket] =>
[secret_key_path] =>
[fcm_server_key] => 1
[messaging_sender_id] => 0
[key_phrase] =>
[disable] => 0
[created] =>
[updated] =>
)
)
I want it like below. expected result
Array
(
[id] => 3
[api_key] => acount266
[auth_domain] => Tester26
[database_url] => vcc.test.acc+27#gmail.com
[project_id] => 12345
[storage_bucket] =>
[secret_key_path] =>
[fcm_server_key] => 1
[messaging_sender_id] => 0
[key_phrase] =>
[disable] => 0
[created] =>
[updated] =>
)
For this I tried like below but no success.
$new = array();
foreach ($data as $v){
$new = array_merge($new , array_values($v)) ;
}
but in my code it's removed key e.g id,api_key, etc....
I need key name also in my new array. please suggest
Remove the array_values
Solution
<?php
$test = array(
array
(
'id' => 3,
'api_key' => 'acount266'
)
);
$new = array();
foreach($test as $v){
$new = array_merge($new, $v);
}
var_dump($new);
Result
array(2) {
["id"]=>
int(3)
["api_key"]=>
string(9) "acount266"
}
According to documentation of PHP as mentioned
reset() function returns the value of the first array element, or
FALSE if the array is empty.
$array = array(
array(
'id' => 3,
'api_key' => 'acount266',
'auth_domain' => 'Tester26',
'database_url' => 'vcc.test.acc+27#gmail.com',
'project_id' => '12345',
'storage_bucket' => '',
'secret_key_path' => '',
'fcm_server_key' => 1,
'messaging_sender_id' => 0,
'key_phrase' => '',
'disable' => 0,
'created' => '',
'updated' => ''
)
);
print_r(reset($test));
I tried this:
$arr = array();
foreach ($examples as $example) {
foreach ($example as $e) {
array_push($arr, $e);
}
}
Don't overcomplicate this, reassigning the first element to the parent array is quick and easy:
<?php
$array =
array (
0 =>
array (
'first' => 'Michael',
'last' => 'Thompson'
)
);
$array = $array[0];
var_export($array);
Output:
array (
'first' => 'Michael',
'last' => 'Thompson',
)
Or:
$array = array_shift($array);

Looping and combine multiple array to one

I have an array looks like this:
Array
(
[0] => Array
(
[name] => color
[value] => red
)
[1] => Array
(
[name] => shape
[value] => square
)
[2] => Array
(
[name] => price
[value] => $15
)
)
I want to have a result like this:
$myArr = array (
'color' => 'red',
'shape' => 'square',
'price' => '$15'
)
I have tried to loop but can not get it to work.
foreach($myArr as $id => $values){
foreach ($values as $key => $value) {
if($key == 'name') {
//add to array key
} else {
//add to that array key value
}
}
}
hope you guys can help me with solution.
You can use array_column and array_combine
$arr = array(
array("name" => 'color',"value" => 'red'),
array("name" => 'shape',"value" => 'square'),
array("name" => 'price',"value" => '$15')
);
$newArr = array_combine(array_column($arr,'name'),array_column($arr,'value'));
echo "<pre>";
print_r( $newArr );
echo "</pre>";
This will result to:
Array
(
[color] => red
[shape] => square
[price] => $15
)
Doc: array_column, array_combine
$a = [
0 => [
"name" => "color",
"value" => "red",
],
1 => [
"name" => "shape",
"value" => "square",
],
2 => [
"name" => "price",
"value" => "$15",
]
];
$b = [];
foreach($a as $v)
{
$b[$v["name"]] = $v["value"];
}
var_dump($b);
result
array(3) {
["color"]=>
string(3) "red"
["shape"]=>
string(6) "square"
["price"]=>
string(3) "$15"
}
$arr = array
(
0 => array
(
'name' => 'color',
'value' => 'red'
),
1 => array
(
'name' => 'shape',
'value' => 'square'
),
2 => array
(
'name' => 'price',
'value' => '$15'
)
);
$final_array =[];
foreach($arr as $key=> $val){
$final_array[$val['name']] = $val['value'];
}
echo "<pre>"; print_r($final_array);

How to replace numeric keys in associative array with their corresponding values

I do have following associative multidimensional array available after json_decode(string, true).
Array
(
[statusCode] => 200
[data] => Array
(
[objects] => Array
(
[0] => deals
[1] => contacts
[2] => accounts
)
[deals] => Array
(
[0] => dealName
[1] => ApprovedBy
[2] => ApprovedDate
[3] => CloseDate
)
[contacts] => Array
(
[0] => contectName
[1] => email
[2] => firstName
[3] => lastName
)
[accounts] => Array
(
[0] => accountName
[1] => creationDate
[2] => ApprovedDate
[3] => accountNumber
)
)
)
It want to replace numeric keys with their corresponding values in arrays like:
[deals] => deals
[contacts] => contacts
[accounts] => accounts
What I tried so far?
$finalIOArray = array();
$integrationObjectsArray = $response['data']['objects'];
foreach($integrationObjectsArray as $integrationObject){
$finalIOArray[$integrationObject] = $integrationObject;
}
This is for only the objects array in the main data array. But I want to replace keys with values in all the sub-arrays in the main data array.
here's a recursive solution to the problem
function updateArray(array $data)
{
$result = array();
foreach ($data as $key => $value) {
if (is_integer($key) && is_string($value)) { // key is integer and value is string
$result[$value] = $value; // update the key
} elseif (is_array($value)) { // value is array
$result[$key] = updateArray($value); // recurse
} else {
$result[$key] = $value; // leave key/value alone
}
}
return $result;
}
print_r(updateArray($arr));
You can do like this
foreach($arr["data"] as $key=>&$data){
$new = array();
foreach($data as $key2=>$value){
$new[$value] = $value;
}
$data = $new;
}
print_r($arr);
Live demo : https://eval.in/858599
I modify my code to suits your needs, please, try it.
$data = [];
foreach($arr["data"] as $key => $example) {
$new = [];
foreach($example as $value) {
$new[$value] = $value;
}
$data[$key] = $new;
}
$arr["data"] = $data;
print_r($arr);
This is a cleaner and more direct method than the others on offer. Use array_combine to bulk reassign keys using values from the subarray.
In my method using foreach, the & before $data means "passing by reference" . http://php.net/manual/en/language.references.pass.php This effectively allows the modification of the original array data without writing the keys that lead to the specific deep element.
Code:
$arr = Array
(
"statusCode" => 200,
"data" => Array
(
"objects" => Array
(
"0" => deals,
"1" => contacts,
"2" => accounts
),
"deals" => Array
(
"0" => dealName,
"1" => ApprovedBy,
"2" => ApprovedDate,
"3" => CloseDate
),
"contacts" => Array
(
"0" => contectName,
"1" => email,
"2" => firstName,
"3" => lastName
),
"accounts" => Array
(
"0" => accountName,
"1" => creationDate,
"2" => ApprovedDate,
"3" => accountNumber
)
)
);
foreach($arr["data"] as &$data){
$data=array_combine($data,$data);
}
var_export($arr);
Output:
array (
'statusCode' => 200,
'data' =>
array (
'objects' =>
array (
'deals' => 'deals',
'contacts' => 'contacts',
'accounts' => 'accounts',
),
'deals' =>
array (
'dealName' => 'dealName',
'ApprovedBy' => 'ApprovedBy',
'ApprovedDate' => 'ApprovedDate',
'CloseDate' => 'CloseDate',
),
'contacts' =>
array (
'contectName' => 'contectName',
'email' => 'email',
'firstName' => 'firstName',
'lastName' => 'lastName',
),
'accounts' =>
array (
'accountName' => 'accountName',
'creationDate' => 'creationDate',
'ApprovedDate' => 'ApprovedDate',
'accountNumber' => 'accountNumber',
),
),
)
Or if you prefer functional iteration, this provides the same output.
$arr["data"]=array_map(function ($a){return array_combine($a,$a);},$arr["data"]);
var_export($arr);

PHP search multidimensional array with two keys for value of 3rd key?

I would think this is simple, searching a multidimensional array with two keys to bring back the value of the third. I'm more confused then when I started and unable to get it to work.
Array (
[0] => Array ( [data] => Array ( [name] => Definite Position [Company_ID] => 4 [code] => DEF ) )
[1] => Array ( [data] => Array ( [name] => First Option [Company_ID] => 7 [code] => TNT ) )
[2] => Array ( [data] => Array ( [name] => Second Option [Company_ID] => 4 [code] => SEC ) )
[3] => Array ( [data] => Array ( [name] => Definite Out [Company_ID] => 6 [code] => DBO ) )
I would like to bring back the value of [name] when I have [Company_ID] of 4 and [code] of 'SEC'
Any help would be appreciated. Thanks
It's just a simple loop accessing the data index and then the indexes below that:
$id = 4;
$code = 'SEC';
foreach($array as $values) {
if($values['data']['Company_ID'] == $id && $values['data']['code'] == $code) {
$result = $values['data']['name'];
break; // we found it no need to loop more
}
}
This might help:
<?php
$array = array(
array(
"data" => array(
"name" => "Definite Position",
"Company_ID" => 4,
"code" => "DEF"
)
),
array(
"data" => array(
"name" => "First Option",
"Company_ID" => 7,
"code" => "TNT"
)
),
array(
"data" => array(
"name" => "Second Option",
"Company_ID" => 4,
"code" => "SEC"
)
),
array(
"data" => array(
"name" => "Definite Out",
"Company_ID" => 6,
"code" => "DBO"
)
)
);
/**
* Searches the array for matching criteria
*
* #param array $search Array of criteria to search for (eg. array("Company_ID" => 4, "code" => "SEC"))
* #param array $array The array to search
*
* #return array The elements of the array that matched the criteria
*/
function search($search, $array)
{
$retVal = array();
foreach($array as $k => $v)
{
$found = true;
foreach($search as $sKey => $sVal)
{
if ($v["data"][$sKey] != $sVal)
{
$found = false;
break;
}
}
if ($found)
$retVal[]= $v;
}
return $retVal;
}
$results = search(
array(
"Company_ID" => 4,
"code" => "SEC"
),
$array
);
var_dump($results);
Result:
array(1) {
[0]=>
array(1) {
["data"]=>
array(3) {
["name"]=>
string(13) "Second Option"
["Company_ID"]=>
int(4)
["code"]=>
string(3) "SEC"
}
}
}

Categories