PHP change Array Format like first_name into First Name - php

Suppose I have array like in below.
Array
(
[0] => agent_name
[1] => first_name
[2] => my_last_name
[3] => job
[4] => job_description
)
Now I want to convert this Array into below format.
Array
(
'agent_name' => 'Agent Name',
'first_name' => 'First Name',
'my_last_name' => 'My Last Name',
'job' => 'Job',
'job_description' => 'Job Description',
)
So can anyone help me, how to set like this.
Thanks

First you need to replace the character _ by space and then use the function ucwords to uppercase the first letters of word.
<?php
$arr = array('agent_name', 'first_name', 'last_name', 'job', 'job_description');
$new_arr = array();
foreach($arr as $val){
$new_arr[$val] = ucwords(str_replace("_", " ", $val));
}
print_r($new_arr);
?>

I used the combination of array_map and array_combine to achieve this,
$a = array_combine($a,array_map(function($val) {
return implode(' ',array_map('ucfirst',explode('_', $val)));
}, $a));
print_r($a);
Here is working demo.

I used array_combine for this
$Main_Array = array('agent_name','first_name','my_last_name','job','job_description');
$New_array = array();
foreach ($Main_Array as $key => $value) {
$New_array[] = ucwords(str_replace('_',' ',$value));
}
$get_result = array_combine($Main_Array,$New_array);
echo '<pre>';
print_r($get_result);

Why not just a simple foreach that works on the same array...
<?php
$data = array
(
0 => 'agent_name',
1 => 'first_name',
2 => 'my_last_name',
3 => 'job',
4 => 'job_description'
);
foreach ( $data AS $k => $v )
{
$data[$v] = ucwords ( str_replace ( '_', ' ', $v ) );
unset ( $data[$k] );
}
print_r ( $data );
?>

Related

How to merge array using UUID value

I have the following code :
<?php
$arr1 = array();
$arr1[] = ['UUID' => '123a-123a', 'name' => 'A1'];
$arr1[] = ['UUID' => '123b-123b', 'name' => 'B1'];
$arr1[] = ['UUID' => '123c-123c', 'name' => 'C1'];
$arr2 = array();
$arr2[] = ['UUID' => '123a-123a', 'name' => 'A2'];
$arr2[] = ['UUID' => '123b-123b', 'name' => 'B2'];
$arr2[] = ['UUID' => '123c-123c', 'name' => 'C2'];
$new_arr1 = array();
foreach ($arr1 as $key => $value) {
if(isset($new_arr1[$value['UUID']])){
$new_arr1[$value['UUID']] += ['name_a' => $value['name']];
}else{
$new_arr1[$value['UUID']] = ['name_a' => $value['name']];
}
}
$new_arr2 = array();
foreach ($arr2 as $key => $value) {
if(isset($new_arr2[$value['UUID']])){
$new_arr2[$value['UUID']] += ['name_1' => $value['name']];
}else{
$new_arr2[$value['UUID']] = ['name_2' => $value['name']];
}
}
$final_array = array_combine($new_arr1, $new_arr2);
var_dump($final_array);
Which give me the following error :
Warning: Array to string conversion in /home/user/scripts/code.php on line 32
Snippet :
https://sandbox.onlinephpfunctions.com/c/cf5fd
I want to use the UUID as an array id.
here is the expected output :
Array
(
[123a-123a] => Array
(
[name_1] => A1
[name_2] => A2
)
[123b-123b] => Array
(
[name_1] => B1
[name_2] => B2
)
[123c-123c] => Array
(
[name_1] => C1
[name_2] => C2
)
)
Instead of use array_combine you need to use array_merge_recursive because is multidimensional
Snippet:
https://sandbox.onlinephpfunctions.com/c/eae35
Reference:
array_merge_recursive
No array_combine nor intermediate arrays needed, just construct new array from those you already have:
$arr1 = array();
$arr1[] = ['UUID' => '123a-123a', 'name' => 'A1'];
$arr1[] = ['UUID' => '123b-123b', 'name' => 'B1'];
$arr1[] = ['UUID' => '123c-123c', 'name' => 'C1'];
$arr2 = array();
$arr2[] = ['UUID' => '123a-123a', 'name' => 'A2'];
$arr2[] = ['UUID' => '123b-123b', 'name' => 'B2'];
$arr2[] = ['UUID' => '123c-123c', 'name' => 'C2'];
$final_array = [];
foreach( array_merge($arr1, $arr2) as $entry ){
if( empty( $final_array[$entry['UUID']] ) )
$final_array[$entry['UUID']] = ['name_1' => $entry['name']];
else
$final_array[$entry['UUID']][ 'name_' . (count( $final_array[$entry['UUID']] ) + 1) ] = $entry['name'];
}
print_r($final_array);
array_combine creates an array by using one array for keys and another for its values. In your case, each of the 2 arrays have individual subarrays in them. Hence the error when it tries to make one of the subarrays as a string(which it can't).
In your code, you can use a single $new_arr and the make the code more concise with the null coalescing operator(??) like below:
<?php
$new_arr = array();
foreach (array_merge($arr1,$arr2) as $key => $value) {
$new_arr[$value['UUID']] = $new_arr[$value['UUID']] ?? [];
$new_arr[$value['UUID']] += [('name_' . (count($new_arr[$value['UUID']]) + 1)) => $value['name']];
}
print_r($new_arr);
Online Demo

Access and join two columns in an array separately

I have below array,
Array
(
[1] => Array
(
[0] => Array
(
[location] => X33
[usernumber] => 1
[order] => XX
[part_number] => Hi
)
[1] => Array
(
[location] => X33
[usernumber] => 1
[order] => YY
[part_number] => 68730
)
)
I want desired output string to echo as below,
'Hello ur oder - XX, YY, part number-Hi, 68730'
How to achieve this output? I was thinking to run a foreach loop, but I'm not sure how I could convert this to a string.
Run a foreachloop and concat
$orderNumber = '';
$partnumber = '';
foreach ($yourArray as $array) {
if ($orderNumber !="") {
$orderNumber.=",";
}
$orderNumber.= $array['order'];
if ($partNumber !="") {
$partNumber.=",";
}
$partNumber.= $array['part_number'];
}
echo "Hello ur order - ".$orderNumber." part number-". $partNumber;
#Frayne Konoks Solution is a nice oneliner:
His Solution with quotes fixed :)
echo 'Hello, ur order - '.implode(", ", array_column($var[1], 'order')).', '.'part number-'.implode(", ", array_column($var[1], 'part_number'))."'";
$var is your array.
Working example:
http://sandbox.onlinephpfunctions.com/code/c95545bdf9d9216d6c80cc06542517e596a0360a
Your must help this code:
<?php
$array = [
[
[
'order' => 1,
'part_number' => 1
],
[
'order' => 2,
'part_number' => 2
]
]
];
$orders = [];
$partnumber = [];
foreach($array as $v) {
foreach($v as $item) {
$orders[] = $item['order'];
$partnumber[] = $item['part_number'];
}
}
$str = sprintf("Hello ur oder - %s, part number-%s", implode(', ', $orders), implode(', ', $partnumber));
echo $str;
Result:
Hello ur oder - 1, 2, part number-1, 2
I changed the array structure a little bit. The code below would be of help:
$arr = array(
array(
'location' => 'X33',
'usernumber' => '1',
'order' => 'XX',
'part_number' => 'Hi',
),
array(
'location' => 'X33',
'usernumber' => '1',
'order' => 'YY',
'part_number' => '68730',
)
);
$order = '';
$p_no = '';
foreach ($arr as $ar) {
$order .= $ar['order'] . ',';
$p_no .= $ar['part_number'] . ',';
}
$order = rtrim($order, ',');
$p_no = rtrim($p_no, ',');
$final_str = 'Hello ur order - ' . $order . ' part number - ' . $p_no;
echo $final_str;
It's as simple as:
foreach($array[1] as $item){
echo "Hello ur order - " . $item["order"] . ", " $item["location"] . ", part number-" . $item["order"] . ", " . $item["part_number"];
}

Laravel/PHP create an array from array

Hey guys I'm confused about how to create an array using specific keys from my pre-existing array.
Laravel controller
public function index()
{
$content = Page::find(1)->content->toArray();
return View::make('frontend.services', compact('content'));
}
$content is an array that looks similar to
array (
0 => array (
'id' => '1',
'page_id' => '1',
'name' => 'banner_heading',
'content' => 'some content', ),
1 => array (
'id' => '2',
'page_id' => '1',
'name' => 'banner_text',
'content' => 'some other content' )
)
And I want it recreate this array to look like this
array (
0 => array (
'banner_heading' => 'some content'
),
1 => array (
'banner_text' => 'some other content'
)
)
How can I move the keys name and content to equal their values as a single row in the array?
I greatly appreciate any advice.
PHP >= 5.5.0:
$result = array_column($content, 'content', 'name');
PHP < 5.5.0:
foreach($content as $key => $array) {
$result[$key] = array($array['name'] => $array['content']);
}
You mean
$newContent = array();
foreach ($content as $record) {
$newContent[] = array($record['name'] => $record['content']);
}
?
I don't know Laravel, but i believe that your solutions should be similar to this :
$newArray= array();
foreach($content as $key => $value)
{
$newArray[] = $value["banner_heading"];
}
return View::make('frontend.services', compact('newArray'));
Or at least it should be something similar with this.

How do I get corresponding keys to another key from multidimensional array?

I have a multidimensional array in the following format:
$array = array (
0 =>
array (
'date' => '2013-03-25',
'name' => 'Bob',
'time' => '11'
),
1 =>
array (
'date' => '2013-03-25',
'name' => 'Brian',
'time' => '13'
),
2 =>
array (
'date' => '2013-03-26',
'name' => 'Jack',
'time' => '14'
),
3 =>
array (
'date' => '2013-03-26',
'name' => 'Bob',
'time' => '14'
)
);
I am trying to get the names and corresponding times for each date. I have got the names using the following method:
$array2 = array();
foreach($array as $item) {
$array2[$item['date']][] = $item['name'];
}
and then using:
foreach($array2[$date] as $name)
to run a query on the names returned. But I am not sure how to get the corresponding 'time' key for each 'name' key in the second foreach loop.
Why you don't want to store both name and time for each date key?
$array2 = array();
foreach ($array as $item) {
$array2[$item['date']] []= array($item['time'], $item['name']);
}
You can reach name and time with this code:
foreach ($array2 as $row) {
$name = $row[0];
$time = $row[1];
}
You can try
$list = array();
foreach ( $array as $k => $item ) {
$list[$item['date']][] = array(
$item['name'],
$item['time']
);
}
foreach ( $list as $date => $data ) {
echo $date, PHP_EOL;
foreach ( $data as $var ) {
list($name, $time) = $var;
echo $name, " ", $time, PHP_EOL;
}
echo PHP_EOL;
}
Output
2013-03-25
Bob 11
Brian 13
2013-03-26
Jack 14
Bob 14
try the following:
foreach($array as $item) {
$array2[$item['date'][] = array('name' => $item['name'], 'time' => $item['time']);
}
foreach($array2[$date] as $name) {
echo $name['name'] . ' => ' . $name['time'] . "\n";
}

how to merge multidimensional arrays whilst preserving all unique key/values?

is there are in build php function or I have to write my own one to merge two multidimensional arrays like that
$list1 = array("school1" => array('string1','string2'));
$list2 = array("school1" => array('string1','string3'),
"school2" => array('string1','string4','string5')
);
into array where nothing will be overwritten or omitted. I want to have only unique values in the the 'second array'. Meaning that array school1 will contain string string1 once only
Array ( [school1] => Array ( [0] => string3 [1] => string2 [2] => string1 )
[school2] => Array ( [0] => string5 [1] => string4 [2] => string1 ) )
ideal would be if I can have the second array = string1, string2 .... sorted desc
my solution
function merge_db_lists ($list1, $list2) {
$final_array = array();
$final_array = go_through_list($list1, $final_array);
$final_array = go_through_list($list2, $final_array);
return $final_array;
}
function go_through_list($list,$output){
foreach (array_keys($list) as $key){
if (array_key_exists($key, $output)){
foreach ($list[$key] as $item ){
$output[$key][] = $item;
}
arsort($output[$key]);
}
else{
$output[$key] = $list[$key];
}
}
return $output;
}
I had a similar need because I needed to merge n-dimensional arrays containing configuration values, so I ended up writing a function, I just expanded it a bit to apply to n-dimensional arrays.
/**
* Recursively merges $array2 to $array1 while keeping the $array2 values
* and keys unique.
*
* #param array $array1 - destination array
* #param array $array2 - array containing new values
* #return array
*/
public function arraysMergeUnique($array1, $array2)
{
foreach ($array2 as $k => $v)
{
if ( is_array($array1) )
{
// If the meaning the value is a string, and doesn't already exist, add it
if ( is_string($v) && ! in_array($v, $array1) )
{
$array1[] = $v;
}
// If the value's an array, make a recursive call with it
else if ( is_array($v) )
{
if ( isset($array1[$k]) )
{
$array1[$k] = $this->arraysMergeUnique($array1[$k], $v);
}
else
{
$array1[$k] = $v;
}
}
}
else
{
$array1 = array($v);
}
}
return $array1;
}
For example, if your list was even deeper, if 'school1' contained 'class1':
$list1 = array(
'school1' => array(
'string1',
'string2',
'class 1' => array(
'student 1',
)
)
);
$list2 = array(
'school1' => array(
'string1',
'string3',
'class 1' => array(
'student 1',
'student 2',
),
'class 2' => array(
'student 3',
),
),
'school2' => array(
'string1',
'string4',
'string5'
)
);
the resulting array would merge it fully:
$result = array(
'school1' => array(
'string1',
'string2',
'class 1' => array(
'student 1',
'student 2'
),
'string3',
'class 2' => array(
'student 3'
)
),
'school2' => array(
'string1',
'string4',
'string5'
)
);
The function should probably be written so that it works with references, and not values like this one, which would greatly improve performance with big arrays, but this one works just fine with smaller ones.

Categories