Creating Associative array (hardcoded key) from foreach in PHP - php

I have an array called $arr containing some information about users. Using $arr I want to create a new associative array with specific keys. That's what I got so far:
$groups = [];
foreach($arr as $val) {
$groups['first_key_name'] = $val->ID;
$groups['second_key_name'] = $val->login;
}
What I'm trying to achieve is a new array that has the following format:
'first_key_name' => $val->ID
'second_key_name' => $val->login
'first_key_name' => $val->ID
'second_key_name' => $val->login
The problem with my current approach is when I var_dump($groups) I only get one key with an empty value although the array should contain at least 10 entries.
The output of var_dump($groups):
array:1 [▼
"first_key_name" => "4"
]
What am I doing wrong?

You are overwriting your variables each time round the loop in this code
$groups = [];
foreach($arr as $val) {
$groups['first_key_name'] = $val->ID;
$groups['second_key_name'] = $val->login;
}
So instead do
$groups = [];
foreach($arr as $val) {
$groups[] = [
'first_key_name' => $val->ID
'second_key_name' => $val->login
];
}
This will create something like this
[0]
[
'first_key_name' = 1,
'second_key_name' = 99
]
[1]
[
'first_key_name' = 2,
'second_key_name' = 199
]
etc

You approach is overwriting the key value every time. That's why you need to use 2d array.
You can try like this:
$groups = [];
foreach($arr as $val) {
$groups[] = ['first_key_name' => $val->ID, 'second_key_name' => $val->login];
}

What happens here, is you are overwriting first_key_name and second_key_name in each turn of the loop. But you want to get an array with the new key=>value pairs.
To achieve that you have to append a new item to your array called $groups, like this:
$groups = [];
foreach ($arr as $val) {
$groups[] = [
'first_key_name' => $val->ID,
'second_key_name' => $val->login
];
}
You may also use array_map for this:
$groups = array_map(function ($val) {
return [
'first_key_name' => $val->ID,
'second_key_name' => $val->login,
];
}, $arr);

Related

Foreach Json Array

I have array, where get_# have random number. Need to foreach all items [result][result][get_#RAND_NUM#] and take [id], [name].
Thanks!
Array:
-[result]
--[result]
---[get_1]
----[id] = "1"
----[name] = "dog"
---[get_6]
----[id] = "53"
----[name] = "cat"
According to PHP manual the foreach makes an iteration over array or object. foreach provides $key and $value options. From this $key var you can get the random number you expect.
The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable.
$data = ['result' => [
'result' => [
'get_1' => ['id' => 1, 'name' => 'doc'],
'get_6' => ['id' => 2, 'name' => 'cat'],
]
]];
$new_data = [];
foreach ($data['result']['result'] as $key => $val) {
// If you want to get the random number uncomment the below line
// $random_no = explode('_', $key)[1]; echo $random_no;
echo "For key {$key}, id = {$val['id']} and name = {$val['name']} </br>";
$new_data[] = ['id' => $val['id'], 'name' => $val['name']];
}
print '<pre>';
print_r($new_data);
Demo

Return all arrays inside foreach loop

How to return all array values inside foreach loop. Return is working fine and no error but is only one record. If i have 10 records in database, It supposed to be all records. What did i missed this code? thanks for your help.
PHP
function myfunction(){
$query ="SELECT * from tbl_data";
$stmt = $this->getConnection()->prepare($query);
$stmt->execute();
foreach ($stmt->fetchAll() as $value) {
//custom value
$customval = 1;
$array = array([
"ID" => $value['ID'],
"name" => $value['name'],
"staus" => $value['status'],
"customval" => $customval,
]);
}
return $array;
}
You are currently actually just overwriting $array, you need to push the new data to it instead.
$array = array();
foreach ($stmt->fetchAll() as $value) {
//custom value
$customval = 1;
$array[] = [
"ID" => $value['ID'],
"name" => $value['name'],
"staus" => $value['status'],
"customval" => $customval,
];
}
return $myArray;
You are assigning $array on every iteration, overwriting the previous value.
Maybe you want to create an array of arrays:
$array = array();
foreach ($stmt->fetchAll() as $value) {
//custom value
$customval = 1;
array_push($array, array([
"ID" => $value['ID'],
"name" => $value['name'],
"staus" => $value['status'],
"customval" => $customval,
]));
}
return $array;
You are only getting one value returned because you are overwriting the value of the array each time.
You need to push the new values each loop iteration.
$myArray = array();
foreach ($stmt->fetchAll() as $value) {
//custom value
$customval = 1;
array_push($myArray, array([
"ID" => $value['ID'],
"name" => $value['name'],
"staus" => $value['status'],
"customval" => $customval,
]));
}
return $myArray;
This will return an array of arrays.

Get certain key and it's value in multidimentional array in php

Suppose I have this array,
$cast = [
'jon' => [
'fullname' => 'Jon Snow',
'class' => 'warrior',
],
'margery' => [
'fullname' => 'Margery Tyell',
'class' => 'politician'
]
];
How do I get the key and it's certain value only? like this,
$name = ['jon'=>'Jon Snow', 'margery'=>'Margery Tyrell'];
Is there any function that support this, so It doesn't have to be loop ?
Any answer will be appreciated!
You can iterate through the multidimensional array, and add the key and the value at index fullname of the inner array in a new one-dimensional array like this:
$names = [];
foreach ($cast as $character => $character_details) {
$names[$character] = $character_details['fullname'];
}
EDIT Alternatively, if you don't want to loop through the elements, you could use array_map function which takes a function as an argument where you can specify how to map each element of the array. In your case, you would simply return the fullname of an element.
$names = array_map(
function ($value) {
return $value['fullname'];
},
$cast
);
I guess that you have iterate over it and extract only interesting you keys. Here you have an example:
function getValuesForKey($array, $key){
$result = [];
foreach($array as $k => $subarray){
if(isset($subarray[$key])){
$result[$k] = $subarray[$key];
}
}
return $result;
}

how to modify array that each item is array in php (clarify in description)

i had a array to each its item was object , i've converted that array with following code :
json_decode(json_encode($array), true)
that the result of code was a array like this :
[
'1'=>[
'slug'=>'a'
'title'=>'foo'
],
'2'=>[
'slug'=>'b'
'title'=>'bar'
],
'3'=>[
'slug'=>'c'
'title'=>'foo'
],
]
now i want to covert this array to somethings like this
[
'a'=>'foom',
'b'=>'bar',
'c'=>'foo',
]
how can i do it ??
Use foreach and array_combine()
foreach ($your_array as $key => $value) {
// get all the keys in $slug array
$slug[] = $value['slug'];
// get all the values in $title array
$title[] = $value['title'];
}
// finally combine and get your required array
$required_array = array_combine($slug, $title);
I think it can also be acheived with -
$requiredArray = array_combine(
array_column($your_array, 'slug'),
array_column($your_array, 'title')
);
You have to iterate over the initial array and create the new one like this:
$array = [
'1'=>[
'slug'=>'a'
'title'=>'foo'
],
'2'=>[
'slug'=>'b'
'title'=>'bar'
],
'3'=>[
'slug'=>'c'
'title'=>'foo'
],
];
$result = [];
foreach($array as $elem){
$index = $elem["slug"];
$value= $elem["title"];
$result[$index] = $value;
}
foreach($array as $elem){
$result[$elem["slug"]] = $elem["title"];
}

Access and explode comma-delimited data from multidimensional array then populate a new 2d array

I have a multidimensional array containing comma-separated strings like this
[
[
"users" => [
'email' => 'test#yahoo.com ,testuser#yahoo.com',
'username' => 'test,testuser',
'description' => 'description1,description2'
]
]
]
I want to access the users subarray data, explode on delimiters, and create a new associative array of indexed arrays.
Desired result:
$User = array(
'email' => array(
'test#yahoo.com',
'testuser#yahoo.com'
),
'username' => array(
'test',
'testuser'
),
'description' => array(
'description1',
'description2'
)
);
For only one index:
$arrayTwoD = array();
foreach ($valueMult[0]['User'] as $key => $value) {
$arrayTwoD[$key] = array_push(explode(',', $value));
}
If you have multiple indexes in $multArray:
$arrayTwoD = array();
foreach ($multArray as $keyMult => $valueMult) {
foreach ($valueMult['User'] as $key => $value) {
$arrayTwoD[$keyMult][$key] = array_push(explode(',', $value));
}
}
or
$arrayTwoD = array();
foreach ($multArray as $array) {
foreach ($array['User'] as $key => $value) {
$arrayTwoD[$key] = array_push(explode(',', $value));
}
}
try this
$array = array(...); // your array data
$formedArray = array();
foreach ( $array as $arr )
{
foreach ( $arr['user'] as $key => $value )
{
$formedArray[$key] = array_push(explode(",",$value));
}
}
echo "<pre>";
print_r($formedArray);
echo "</pre>";
It's a little bit repetitive, I know, but you can do like this as well:
foreach($array as $users) {
foreach($users as &$value) { // &value is assigned by reference
$users['users']["email"] = explode(",", $value['email']);
$users['users']["username"] = explode(",", $value['username']);
$users['users']["description"] = explode(",", $value['description']);
}
}
But after that, you need to use $value. Refer to the official PHP manual documentation to know more about what the & symbol does here.
Demo
Using array_map() can be used to access the subset data (without declaring any new variables in the global scope) and make iterate calls of preg_split() to separate the delimited values into subarrays.
Code: (Demo)
var_export(
array_map(
fn($csv) => preg_split('/ ?,/', $csv),
$array[0]['users']
)
);

Categories