changing the key description in php array issue - php

I have an array like the one below
Array
(
[0] => Array
(
[name] => Alex
[age] => 30
[place] => Texas
)
[1] => Array
(
[name] => Larry
[age] => 28
[place] => Memphis
)
)
How would I change the key names? Like "name" to "firstname", "age" to "years", "place" to "address"?

Use a foreach loop to iterate over your array, and then use array_combine in conjunction with array_values() to create the new array:
$keys = array('firstname', 'years', 'address');
foreach ($array as & $subarr) {
$subarr = array_combine($keys, array_values($subarr));
}
print_r($array);
Output:
Array
(
[0] => Array
(
[firstname] => Alex
[years] => 30
[address] => Texas
)
[1] => Array
(
[firstname] => Larry
[years] => 28
[address] => Memphis
)
)
Online demo

array_map is your friend,
$users = array_map(function($user) {
return array(
'firstname' => $user['name'],
'years' => $user['age'],
'location' => $user['place']
);
}, $users);
DEMO.

I believe that the only way to do this is to create a new array and assign each value with old key to value with new key.
<?php
//$originalArray is array from the question.
for($i=0; $i<=count($originalArray); $i++){
$originalArray[$i] = rekeyArray($originalArray[$i]);
}
function rekeyArray($a){
$result = array();
if(isset($a['name']))
$result['firstname'] = $a['name'];
if(isset($a['age']))
$result['years'] = $a['age'];
if(isset($a['place']))
$result['address'] = $a['place'];
return $result;
}
?>

Related

Make associative array of unique values from column containing arrays

Array
(
[0] => Array
(
[id] => 21153
[genre] => ["History","Drama", "Thriller"]
)
[1] => Array
(
[id] => 21152
[genre] => ["ACTION"]
)
[2] => Array
(
[id] => 21151
[genre] => ["ROMANTIC"]
)
[3] => Array
(
[id] => 21150
[genre] => ["Drama"]
)
)
I have with the above array and I want to convert that array to an unique array as mentioned below, and there should be any duplicate values.
Array(
[History] => "History"
[ACTION] => "ACTION"
[ROMANTIC] => "ROMANTIC"
[Drama] => "Drama"
[Thriller]=>"Thriller"
)
I don't really get how the resulting array makes any sense, but here you are:
Loop through the array, loop through the genres and push items to a new array.
<?
$a = Array
(
[
"id" => 21153,
"genre" => ["History","Drama", "Thriller"]
],
[
"id" => 21152,
"genre" => ["ACTION"]
]
);
$result = [];
foreach($a as $b) {
foreach($b['genre'] as $genre) {
$result[$genre] = $genre; // don't need to check if it exists already, because we'll overwrite it anyway.
}
}
echo "<pre>";
print_r($result);
echo "</pre>";
// output:
Array
(
[History] => History
[Drama] => Drama
[Thriller] => Thriller
[ACTION] => ACTION
)
It can be done by using foreach() loop and in_array() function like below
$myArray=array();
$array = array(
array("id"=>21153,"genre"=>array("History","Drama", "Thriller")),
array("id"=>21152,"genre"=>array("ACTION")),
array("id"=>21151,"genre"=>array("ROMANTIC")),
array("id"=>21150,"genre"=>array("Drama"))
);
foreach($array as $arr){
foreach($arr as $genres){
if(is_array($genres)){
foreach($genres as $elem){
if (!in_array($elem, $myArray))
{
$myArray[$elem]=$elem;
}
}
}
}
}
print_r($myArray);
This is a function that resolves what you ask, though I'm not sure it is quite useful to have value and key being identical. I'm just looping over all genders and add only the ones I don't already have store in returning array. probably a bit dangerous with your code because it is case sensitive
function getGenders(array $rawValues) :array {
$distinctGenders = [];
foreach ($rawValues as $row) {
foreach ($row["genre"] as $gender) {
if (!in_array($gender, $distinctGenders)) {
$distinctGenders[$gender] = $gender;
}
}
}
return $distinctGenders;
}
By doing the changes, I have fixed this,
$responseData = Array(
[0] => Array
(
[id] => 21153
[genre] => ["History","Drama", "Thriller"]
)
[1] => Array
(
[id] => 21152
[genre] => ["ACTION"]
)
[2] => Array
(
[id] => 21151
[genre] => ["ROMANTIC"]
)
[3] => Array
(
[id] => 21150
[genre] => ["Drama"]
)
foreach ($responseData as $data){
$strReplace = str_replace(array('[',']') , '' , $data['genre']);
$explodeData[] = explode(',', $strReplace);
}
And the output after exploding is :
$explodeData = Array
(
[0] => Array
(
[0] => "History"
[1] => "Drama"
[2] => "Thriller"
)
[1] => Array
(
[0] => "ACTION"
)
[2] => Array
(
[0] => "ROMANTIC"
)
[3] => Array
(
[0] => "Drama"
)
)
And finally by the foreach loop :
foreach ($explodeData as $arr) {
foreach ($arr as $genres) {
if (!in_array($genres, $myArray)) {
$myArray[$genres] = $genres;
}
}
}
And finally the required output comes as below :
Array(
["History"] => "History"
["Drama"] => "Drama"
["Thriller"] => "Thriller"
["ACTION"] => "ACTION"
["ROMANTIC"] => "ROMANTIC"
)
Flatten the column of data.
Assign keys from the values (this ensures uniqueness).
Code: (Demo)
$array = [
["id" => 21153, "genre" => ["History", "Drama", "Thriller"]],
["id" => 21152, "genre" => ["ACTION"]],
["id" => 21151, "genre" => ["ROMANTIC"]],
["id" => 21150, "genre" => ["Drama"]]
];
$flat = array_merge(...array_column($array, 'genre'));
var_export(
array_combine($flat, $flat)
);
Output:
array (
'History' => 'History',
'Drama' => 'Drama',
'Thriller' => 'Thriller',
'ACTION' => 'ACTION',
'ROMANTIC' => 'ROMANTIC',
)

Get all value from array

I don't know How to get "name" value from all array ?
Any one please help me
I have some array like this
Array
(
[0] => Array
(
[name] => Jon
[phone] =>
[relation] => wife
[age] => 43
[relative_education] => 4
)
[1] => Array
(
[name] => John
[phone] => 123456789
[relation] => son
[age] => 24
[relative_education] => 10
)
[2] => Array
(
[name] => Amy
[phone] => 456789123
[relation] => Son
[age] => 21
[relative_education] => 12
)
)
Thanks in advance.
Try this
$name = array_column($data, 'name');
print_r($name);
$names = array_map(function($user) {
return $user['name'];
}, $users);
You can loop the array to get the values.
If your array is $arr then use the below code to get the values
//$arr = YOUR ARRAY
$names = array();
foreach($arr as $val) {
$names[] = $val['name'];
}
print_r($names);

PHP merge 2 array with same key

Hi everyone how I can merge/push one array to another to specific keys? Here is my arrays:
// Array 1
Array
(
[1] => Array
(
[name] => test
)
)
// Array 2
Array
(
[1] => Array
(
[age] => 25
)
)
I want this result:
Array
(
[1] => Array
(
[name] => test
[age] => 25
)
)
I use PHP and will be very grateful if someone help me. Thanks in advance!
$arr = [ 1 => [ "name" => "Test" ] ];
$arr2 = [ 1 => [ "age" => 25 ] ];
foreach ($arr as $key => $value) {
if (isset($arr2[$key])) {
$arr[$key] = array_merge($value,$arr2[$key]);
}
}
print_r($arr);
Check the output at https://eval.in/602680
Just add them together:
<?php
$array1 = array('name' => 'test');
$array2 = array('age' => 21);
var_dump($array1 + $array2);

Sorting multidimensional array, upper case being sorted before lowercase

Using the below for sorting a multidimensional array by screen name:
$sortArray = array();
foreach($members as $member){
foreach($member as $key=>$value){
if(!isset($sortArray[$key])){
$sortArray[$key] = array();
}
$sortArray[$key][] = $value;
}
}
$orderby = "screen_name";
array_multisort($sortArray[$orderby],SORT_ASC,$members);
But uppercase is being sorted before lowercase:
Allan
Brenda
Greg works
But Frank comes before dan
There's a lot out there on sorting arrays, but I finally got this working using the above, wanted to see if there was an easy way to fix it?
uasort() should work for you
<?php
// custom sort function
function sort_by_screen_name($a, $b) {
// compare using lowercase strings only
$a = strtolower($a['screen_name']);
$b = strtolower($b['screen_name']);
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
$members = array(
array('screen_name'=>'Greg'),
array('screen_name'=>'Allen'),
array('screen_name'=>'dan'),
array('screen_name'=>'Brenda'),
);
// uasort() like a boss!
uasort($members, 'sort_by_screen_name');
print_r($members);
Output
Array
(
[1] => Array
(
[screen_name] => Allen
)
[3] => Array
(
[screen_name] => Brenda
)
[2] => Array
(
[screen_name] => dan
)
[0] => Array
(
[screen_name] => Greg
)
)
Note: the original array keys are preserved using this method. If you'd like the keys to be rewritten, you can simply use usort().
You can sort this with usort() and a custom sorting function. You can modify this data if you like to see how it suits your own custom details: http://codepad.org/b89HwmbM
$members = array(
array( "loc" => "Ontario", "first" => "Bob", "screen_name" => "fooArt" ),
array( "loc" => "Atlanta", "first" => "Sal", "screen_name" => "TIMMY!" ),
array( "loc" => "Panama", "first" => "Mick", "screen_name" => "Analog" ),
array( "loc" => "Pensacola", "first" => "A", "screen_name" => "Franky" ),
array( "loc" => "McPherson", "first" => "Anna", "screen_name" => "annie9" )
);
usort( $members, 'custom_sort' );
function custom_sort( $m1, $m2 ){
return strtolower( $m1['screen_name'] ) > strtolower( $m2['screen_name'] );
};
The output from this sorting method follows:
Array
(
[0] => Array
(
[loc] => Panama
[first] => Mick
[screen_name] => Analog
)
[1] => Array
(
[loc] => McPherson
[first] => Anna
[screen_name] => annie_23
)
[2] => Array
(
[loc] => Ontario
[first] => Bob
[screen_name] => fooArt
)
[3] => Array
(
[loc] => Pensacola
[first] => A
[screen_name] => Franky
)
[4] => Array
(
[loc] => Atlanta
[first] => Sal
[screen_name] => TIMMY!
)
)

Array in array with foreach

I have a new PHP problem. I have 2 arrays, and I want a third array which is a combination of the first 2. The first array, $arr1, is something like this:
Array (
[0] => name [1] => age
)
The second array, $arr2, is something like this:
Array (
[0] => Array( [0] => Dave [1] => 20 )
[1] => Array( [0] => Steve [1] => 25 )
[2] => Array( [0] => Ace [1] => 23 )
)
And my idea is to create a new array, called $arr3, which should like this:
Array (
[0] => Array( [name] => Dave [age] => 20 )
[1] => Array( [name] => Steve [age] => 25 )
[2] => Array( [name] => Ace [age] => 23 )
)
Can anyone tell me how to do this?
$arr3 = array();
foreach ($arr2 as $person) {
$arr3[] = array_combine($arr1, $person);
}
foreach($arr2 as $subArray){
foreach($subArray as $i=>$val){
$arr3[$arr1[$i]] = $val;
}
}

Categories