How to convert submitted form array to this array on php? - php

Lets suppose i have the following array submitted by a html form:
array(
'firstname' => array('Sara','Jim'),
'lastname' => array('Gibson','Jobs')
);
What i wanna achieve is the following array:
array(
array(
'firstname' => 'sara',
'lastname' => 'Gibson'
),
array(
'firstname' => 'Jim',
'lastname' => 'Jim'
)
);
I need a function to automatically sort the array not manually by entering data but automatically processing array data.

$new_arr = array();
$length = count($arr['firstname']);
for($i = 0; $i < $length; $i++)
{
$new_arr[] = array('firstname' => $arr['firstname'][$i], 'lastname' => $arr['lastname'][$i]);
}

I don't see anything wrong with #Tim Cooper's solution, but if you don't want to mention the keys manually, you can also use:
$new_arr = array();
foreach ($arr as $key => $value)
{
foreach ($value as $numkey => $value2)
{
$new_arr[$numkey][$key] = $value2;
}
}

Related

PHP grouping content of multidimensional array with new structure

I usually use Eloquent so transposing the data is much easier. However i'm struggling to this in vanilla PHP.
I have tried array_map(null, ...$array) however get an error due to it not being an array.
I have got the following keyed array:
[
'email' => [
"william.pool#gmail.com",
"martynleeball#gmail.com"
],
'lastName' => [
'Pool',
'Ball'
],
'firstName' => [
'William',
'Martyn'
],
'id' => [
'j8zwyk',
'1'
]
]
I need to convert this to the following format:
[
0 => [
'email' => "william.pool#gmail.com",
'lastName' => 'Pool',
'firstName' => 'William',
'id' => 'j8zwyk'
],
1 => [
'email' => "martynleeball#gmail.com",
'lastName' => 'Ball',
'firstName' => 'Martyn',
'id' => '1'
]
]
Create new array with length 2 and loop through origin array. In loop insert relevant item into new array.
So if your array has only 2 item per key use
$newArr = [];
foreach($arr as $key=>$item){
$newArr[0][$key] = $item[0];
$newArr[1][$key] = $item[1];
}
But if it has unknown item use
$newArr = [];
foreach($arr as $key=>$item){
foreach($item as $key2=>$item2)
$newArr[$key2][$key] = $item2;
}
Check result in demo
$newArray = [];
foreach ($array as $key => $value) {
for ($i = 0; $i < count($value); $i++) {
$newArray[$i][$key] = $value[$i];
}
}

PHP remove array if subarray empty

my array image just like this, if subarray "name" is empty or null i want delete array, how to do that ?
here my current script
$data = array();
$fixedData = array();
$countyName = array();
$numrow = 2;
echo "<pre>";
// insert to tb participant => 1
foreach($sheet as $key => $row){
$data[] = array(
'name' => $this->split_name($row['B']),
'phone' => $row['D'],
'mobile' => $row['E'],
'institution' => $row['F'],
'departement' => $row['G'],
'address' => $row['H'],
'country' => $row['I'],
);
$numrow++;
}
unset($data[0]); //delete first row
$data = array_values($data);
//loop search data
var_dump ($data);
die();
Assume that you have the following data set,
$array = [
[
'name' => 'not null', 'phone' => 12546
],[
'name' => '', 'phone' => 852147
],[
'name' => null, 'phone' => 96325874
],[
'name' => 'have value', 'phone' => 12546
],
];
You can filter the nulled or empty values like several ways :
1-
foreach ($array as $key => &$value) {
if (empty($value['name']) || is_null($value['name'])) {
$value = null;
}
}
$array = array_filter($array);
2-
$newData = [];
foreach ($array as $key => $value) {
if (!empty($value['name']) && !is_null($value['name'])) {
$newData[] = $value;
}
}
3- using array_walk
$newData = [];
array_walk($array, function ($value, $key) use (&$newData) {
if (!empty($value['name']) && !is_null($value['name'])) {
$newData[] = $value;
}
});
4- using array_filter
$newData = array_filter($array, function ($value) {
if (!empty($value['name']) && !is_null($value['name'])) {
return $value;
}
});
<?php
$data = array();
$fixedData = array();
$countyName = array();
$numrow = 2;
echo "<pre>";
// insert to tb participant => 1
foreach($sheet as $key => $row){
if($this->split_name($row['B'])!=='' && $this->split_name($row['B'])!==NULL){
$data[] = array(
'name' => $this->split_name($row['B']),
'phone' => $row['D'],
'mobile' => $row['E'],
'institution' => $row['F'],
'departement' => $row['G'],
'address' => $row['H'],
'country' => $row['I'],
);
$numrow++;
}
}
//loop search data
var_dump ($data);
die();
I simple put an if condition inside your loop so you can check if your value is null or empty and if it is then you don't fill your new array. Also moved your counter inside the if so you increment it only in a success array push
A more "elegant" way for your if condition is this as well:
if (!empty($this->split_name($row['B'])) && !is_null($this->split_name($row['B'])))

PHP - How to create such array?

The question is simple, I want to create the array below dynamically, but the code I got now only outputs the last row. Is there anybody who knows what is wrong with my dynamically array creation?
$workingArray = [];
$workingArray =
[
0 =>
[
'id' => 1,
'name' => 'Name1',
],
1 =>
[
'id' => 2,
'name' => 'Name2',
]
];
echo json_encode($workingArray);
/* My not working array */
$i = 0;
$code = $_POST['code'];
$dynamicArray = [];
foreach ($Optionsclass->get_options() as $key => $value)
{
if ($value['id'] == $code)
{
$dynamicArray =
[
$i =>
[
'id' => $key,
'name' => $value['options']
]
];
$i++;
}
}
echo json_encode($dynamicArray);
You dont need to have the $i stuff that is adding another level to your array that you dont want.
$code = $_POST['code'];
$dynamicArray = [];
foreach ($Optionsclass->get_options() as $key => $value)
{
if ($value['id'] == $code)
{
$dynamicArray[] = ['id' => $key, 'name' => $value['options'];
}
}
echo json_encode($dynamicArray);
You are creating a new dynamic array at each iteration:
$dynamicArray =
[
$i =>
[
'id' => $key,
'name' => $value['options']
]
];
Instead, declare $dynamicArray = []; above the foreach, and then use:
array_push($dynamicArray, [ 'id' => $key, 'name' => $value['options']);
inside the array.

Multidimensional array looping (PHP) - a better way?

Is there a better/more efficient way to loop through this data?
I need to loop through the array data with the 'Name' first and the 'ListID' second but the external API request generates the array as per the code below (the other way round).
// Array Data
$csList = array(
array(
'ListID' => 'BGERFwQTrHoseE4sweebqwyAxuJ9YU',
'Name' => 'Monthly Newsletter Subscribers'
),
array(
'ListID' => 'kHdUQMbELgMyojuATz9Dsbxz3WViVo',
'Name' => 'Special Mailout'
)
);
// Generate Array Varaibles
foreach($csList as $array => $values) {
foreach($values as $k => $v) {
for($i = 1; $i < count($csList); $i++) {
$csListData[$k][] = $v;
}
}
}
// Loop Data
for($i = 0; $i < count($csList); $i++) {
echo $csListData['Name'][$i].'<br>';
echo $csListData['ListID'][$i].'<br>';
}
It's not at all clear why you're rearranging the data. Loop over the array and access whatever keys you want in whatever order you want.
$csList = array(
array(
'ListID' => 'BGERFwQTrHoseE4sweebqwyAxuJ9YU',
'Name' => 'Monthly Newsletter Subscribers'
),
array(
'ListID' => 'kHdUQMbELgMyojuATz9Dsbxz3WViVo',
'Name' => 'Special Mailout'
)
);
foreach ($csList as $item) {
echo $item['Name'].'<br>';
echo $item['ListID'].'<br>';
}
Your inner for loop is useless. You can use the $array key to get your array as wanted :
foreach($csList as $array => $values) {
foreach($values as $k => $v) {
$csListData[$k][$array] = $v;
}
}
// Loop Data
for($i = 0, $c = count($csList); $i <$c; $i++) {
echo '<br>';
echo $csListData['Name'][$i].'<br>';
echo $csListData['ListID'][$i].'<br>';
}
Also, moving the count() out of the check will avoid to count at every iteration of the loop.
// Array Data
$csList = array(
array(
'ListID' => 'BGERFwQTrHoseE4sweebqwyAxuJ9YU',
'Name' => 'Monthly Newsletter Subscribers'
),
array(
'ListID' => 'kHdUQMbELgMyojuATz9Dsbxz3WViVo',
'Name' => 'Special Mailout'
)
);
You can do as follow:
$newCsList = array();
$newCsList = array_map(function ($val){
return array_reverse($val,true);
},$csList);
The result is like:
**Array (
[0] => Array (
[Name] => Monthly Newsletter Subscribers
[ListID] => BGERFwQTrHoseE4sweebqwyAxuJ9YU
)
[1] => Array (
[Name] => Special Mailout
[ListID] => kHdUQMbELgMyojuATz9Dsbxz3WViVo
)
)**
But for taking each element you can do:
$newCsList = array();
$newCsList = array_map(function ($val){
$my_test_ary = array_reverse($val);
echo $my_test_ary['Name'].'<br/>'.$my_test_ary['ListId'];
},$csList);

Merge and rearrange nested key/values

I have an array like this:
array(
0 => array(
'name' => 'colors',
'options' => array(
array('name'=>'red', 'price'=>'2'),
array('name'=>'blue', 'price'=>'3')
)
),
1 => array(
'name' => 'sizes',
'options' => array(
array('name'=>'small', 'price'=>'5'),
array('name'=>'large', 'price'=>'10')
)
),
);
I want to merge all of the nested options arrays' name/prices into one, so it'll be like this:
array(
'red' => '2',
'blue' => '3',
'small' => '5',
'large' => '10'
);
I have a feeling this is very simple, but anything I try seems too convoluted. Any help would be appreciated.
...and yes, I just posted almost the same question not too long ago. This is a bit different, and what I meant to ask in the first place - oops, sorry.
I'm not sure if this can be done with internal methods such as array_merge(), array_combine(), etc since your structure seems quite special. But how about iterating over the array and building a new one yourself?
function customRearrange($arr) {
$result = array();
foreach ($arr as $group) {
foreach ($group['options'] as $option) {
// prevents values from being overwritten, uncomment if unwanted
if (!array_key_exists($option['name'], $result))
$result[ $option['name'] ] = $option['price'];
}
}
return $result;
}
You need to decide how you will handle collisions, anyway here is same which will give you right direction:
$newArray = array();
foreach ($array as $i => $item)
foreach ($item['options'] as $j => $option)
$newArray[$option['name']] = $option['price'];
Here's another way, assuming the array has been assigned to the variable $a:
<?php
for ($i = 0; $i < count($a); $i++) {
$key = $a[$i]['name'];
$options = $a[$i]['options'];
for ($j = 0; $j < count($options); $j++) {
$optkey = $options[$j]['name'];
$prices[$optkey] = $options[$j]['price'];
}
}
print_r($prices);
Iterate through "options" in the nested array and create a new array :
<?php
$arr = array(
0 => array(
'name' => 'colors',
'options' => array(
array('name'=>'red', 'price'=>'2'),
array('name'=>'blue', 'price'=>'3')
)
),
1 => array(
'name' => 'sizes',
'options' => array(
array('name'=>'small', 'price'=>'5'),
array('name'=>'large', 'price'=>'10')
)
),
);
$group = array();
foreach($arr as $a){
foreach($a['options'] as $op){
$group[$op['name']] = $op['price'];
}
}
print_r($group);
?>

Categories