I have an array data that look like this :
Array (
[0] => Array (
[0] => Name:
[1] => John W.
[2] => Registration ID:
[3] => 36
)
[1] => Array (
[0] =>Age:
[1] => 35
[2] => Height:
[3] => 5'11"
)
[3] => Array (
[0] => Sex:
[1] => M
[2] => Weight:
[3] => 200lbs
)
[4] => Array (
[0] => Address
)
[5] => Array (
[0] => 6824 crestwood dr delphi, IN 46923
))
And I want to convert it to associative array like this :
Array(
['Name']=> John W.
['Registration ID']=> 36
['Age']=> 35
['Height'] => 5'11''
['Sex']=>M
['Weight']=>200lbs
['Address']=>6824 crestwood dr delphi, IN 46923
)
I have no idea at all how to do this, since the supposed to be array column header were also in sequence, so it makes difficult to convert this array.
Any help I appreciate, thx.
Given your origin array is called $origin , you can do it like this:
$merged = array();
foreach($origin as $val) {
$merged = array_merge($merged, $val);
}
$tot = count($merged) - 1;
for ($i=0;$i<$tot;$i+=2) {
$result[$merged[$i]] = $merged[$i+1];
}
var_dump($result); // To test the resulting array
Firstly, I use array_merge() to flatten the $origin array to only one dimension/depth, so we later iterate it (stepping each 2 items per iteration) and assigning each pair of items ($i and $i+1) to the resulting array.
Looks like, for the first 3 children, you can just assign the even value to the previous element as key. Then, assign the fourth one as key for fifth element.
$result = array();
foreach ($array as $key => $value)
{
if ($key < 4) {
$elements = array_values($value);
$result[$elements[0]] = $elements[1];
$result[$elements[2]] = $elements[3];
}
if ($key == 4)
$fifthkey = $value;
if ($key == 5)
$result[$fifthkey] = $value;
}
Also, note that you have to escape your height string quotes.
Related
Ok so I have an array look like this,
Array
(
[0] => Array
(
[0] => order_date.Year
[1] => =
[2] => 2024
),
[1] => Array
(
[0] => order_date.Quarter
[1] => =
[2] => 1
)
)
What I want to do is, in any element of this multidimensional array I want to replace any string that have a . with removing everything after .
So the new array should look like this,
Array
(
[0] => Array
(
[0] => order_date
[1] => =
[2] => 2024
),
[1] => Array
(
[0] => order_date
[1] => =
[2] => 1
)
)
I have tried doing this,
foreach ($filter as $key => $value) {
if(is_array($value)) {
$variable = substr($value[0], 0, strpos($value[0], "."));
$value[0] = $variable;
}
}
print_r($filter);
I'm getting $value[0] as order_date but can't figure out how to assign it to $filter array without affecting other values in array;
The $value variable is not linked with the original array in the foreach loop.
You can make a reference to the original array by using ampersand "&"
foreach ($filter as $key => &$value) { ... }
Or you can use old school key nesting
$filter[$key][0] = $variable;
Please take a look here https://stackoverflow.com/a/10121508/9429832
this will take off values after . in every element of any multidimensional array.
// $in is the source multidimensional array
array_walk_recursive ($in, function(&$item){
if (!is_array($item)) {
$item = preg_replace("/\..+$/", "", $item);
}
});
Does anyone know how I can create an Array?
$string = '3-1-0-1.11,3-1-1-1.12,3-1-2-1.13,3-1-3-1.14,3-2-0-1.02,3-2-1-1.03,3-2-2-1.04,3-2-3-1.05,3-2-4-1.06,3-3-0-3.23,3-3-1-3.24,3-3-2-3.25,3-3-3-3.26';
$array = explode(',', $string);
$last_entry = null;
foreach ($array as $current_entry) {
$first_char = $current_entry[2]; // first Sign
if ($first_char != $last_entry) {
echo '<h2>'. $first_char . '</h2><br>';
}
echo $current_entry[4] . '<br>';
$last_entry = $first_char;
}
I need an Array like this:
Array
(
[1] => Array
(
[0] => 0
[1] => 1
[2] => 2
)
[2] => Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 4
[5] => 5
)
[3] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
)
The first number 3 and other numbers 3 after comma are not important.
Important numbers are second and third numbers in values of $array.
I need categories. Example: if the first (second) number is 1 create Category 1 and subcategory 1 where first (second) number actual is 1.
To create an an array, you need to declare it using array() feature. Below I have created a blank array.
$array = array();
An array with values looks like this
$array = array("string", "string2", "string3");
To add values in an array, you use the array_push method.
array_push($array, "string4");
On multidimensional arrays, declare the array then add the inner array, below is objct oriented
$array = array("string"=>array("innerstring", "innerstring2"), "string2" => array("innerstring3", "innerstring4"), "string3" => array("innerstring5", "innerstring6"));
and procedural
$array=array(array("string", "innerstring", "innerstring2",), array("string2", "innerstring3", "innerstring4"), array("string3", "innerstring5", "innerstring6"));
Try next script:
$string = '3-1-0-1.11,3-1-1-1.12,3-1-2-1.13,3-1-3-1.14,3-2-0-1.02,3-2-1-1.03,3-2-2-1.04,3-2-3-1.05,3-2-4-1.06,3-3-0-3.23,3-3-1-3.24,3-3-2-3.25,3-3-3-3.26';
foreach(explode(',', $string) as $tpl) {
$tpl = explode('-', $tpl);
$tpl[3] = explode('.', $tpl[3]);
$result[$tpl[1]][$tpl[2]][$tpl[3][0]] = !empty($tpl[3][1]) ? $tpl[3][1] : null;
}
var_dump($result);
I have arrays within arrays, all with varying amounts of information. My CSV table currently has the fields Name, Email, and Phone Number.
Below is my array;
Array
(
[0] => Array
(
[0] => Name
[1] => Email
[2] => Phone Number
)
[1] => Array
(
[0] => Mick
[1] => mick#mick.com
[2] => 01234 324234
)
[2] => Array
(
[0] => james
[1] => james#james.com
[2] =>
)
[3] => Array
(
[0] => reg
[1] => reg#reg.com
[2] => 10293 467289
)
)
I wish to loop through and remove these null values and combine the Email and Phone Number into Info end up with an array which resembles
Array
(
[0] => Array
(
[0] => Name
[1] => Info
)
[1] => Array
(
[0] => Mick
[1] => mick#mick.com + 01234 324234
)
[2] => Array
(
[0] => james
[1] => james#james.com
)
[3] => Array
(
[0] => reg
[1] => reg#reg.com + 10293 467289
)
)
Here is my current script, I am recienving the error;
<b>Warning</b>: array_filter() expects parameter 2 to be a valid callback, no array or string given in <b>C:\Users\Lydia\Documents\XAMPP\htdocs\CSV.php</b> on line <b>21</b><br />
every time that I loop through the changeRow() function, any help greatly appreciated
index.php
<?php
include 'CSV.php';
header('Content-type: text/plain');
$file = read_csv('Book1.csv');
$input = changeRow($file);
CSV.php
....
....
function changeRow($rows){
$len = count($rows);
for($i = 0; $i < $len; $i++){
$rows = array_filter($rows[0],0);
}
}
Can use array_map() instead of foreach(). Example:
$file = read_csv('Book1.csv');
$input = array_map(function($v){
$phone = (isset($v[2]) && $v[2]) ? ' + '. $v[2] : '';
return array($v[0], $phone);
},$file );
if(isset($result[0][1])) $result[0][1] = 'Info';
print '<pre>';
print_r($input);
print '</pre>';
I'll provide two methods that output the requested array structure. (PHP Demo Link) These methods iterate the array, check if the iteration is dealing with the "column heading" subarray or not, then conditionally appending the value from subarray element [2] to subarray element [1] using + as glue.
Method #1: foreach()
foreach($array as $index=>$item){
if(!$index){
$result[]=['Name','Info'];
}else{
$result[]=[$item[0],$item[1].(strlen($item[2])?" + $item[2]":'')];
}
}
var_export($result);
Method #2 array_map()
var_export(
array_map(function($index,$item){
if(!$index){
return ['Name','Info'];
}else{
return [$item[0],$item[1].(strlen($item[2])?" + $item[2]":'')];
}
},array_keys($array),$array)
);
Output: (from either method)
array (
0 =>
array (
0 => 'Name',
1 => 'Info',
),
1 =>
array (
0 => 'Mick',
1 => 'mick#mick.com + 01234 324234',
),
2 =>
array (
0 => 'james',
1 => 'james#james.com',
),
3 =>
array (
0 => 'reg',
1 => 'reg#reg.com + 10293 467289',
),
)
ps. If you want to remove the $index==0 check that is iterated each time, you can manually overwrite the first subarray after the loop is finished like this: (PHP Demo Link) *this just means you will be "writing" data to the first subarray twice.
foreach($array as $item){
$result[]=[$item[0],$item[1].(strlen($item[2])?" + $item[2]":'')];
}
$result[0]=['Name','Info'];
var_export($result);
or
$result=array_map(function($item){return [$item[0],$item[1].(strlen($item[2])?" + $item[2]":'')];},$array);
$result[0]=['Name','Info'];
var_export($result);
pps. "Passing by Reference" can be used for this task, but I've elected not to use &$array because it can risk causing trouble "downscript" and many developers advise against using it until other methods are inadequate. Here is what that can look like: (PHP Demo Link)
foreach($array as &$item){
if(strlen($item[2])) $item[1].=" + $item[2]";
unset($item[2]);
}
$array[0]=['Name','Info'];
var_export($array);
unset($item); // var_export($item); // ($item = NULL)
It seems I have a problem regarding arrays that would change the value of first array depending on the value and position of the second array. It would seem to hard to explain in words, I'll give an example to make this a little bit more of understanding.
I have this first array
Array
(
[0] => one
[1] => two
[2] => three
[3] => four
[4] => five
)
and this is my second array
Array
(
[0] =>
[1] => cat
[2] =>
[3] => dog
[4] =>
)
and my desired result should be like this
Array
(
[0] => one
[1] => cat
[2] => three
[3] => dog
[4] => five
)
so if I changed my second array into this
Array
(
[0] =>
[1] =>
[2] =>
[3] => dog
[4] => cat
)
The result would be like this
Array
(
[0] => one
[1] => two
[2] => three
[3] => dog
[4] => cat
)
So meaning, the second array would be like the replacement of the first array.
Well I used array_diff to get the difference of the two arrays and that's where I'm stuck.
Any help would be appreciated though.
There may be a better way but you could do something like:
for ($i = 0; $i < count($array1); $i++) {
if ($array2[$i] == null || $array2[$i] == "") {
$newArray[$i] = $array1[$i];
}
else {
$newArray[$i] = $array2[$i];
}
}
$newArray will contain all values from $array1 unless a non-null or empty value exists in $array2 (based on the array index), in which case it will overwrite the value that was in $array1.
Maybe this link about
array_merge
could be usefull
http://php.net/manual/en/function.array-merge.php
I think this should work:
foreach($second_array as $k => $v)
{
if($v != "")
{
$first_array[$k] = $v;
}
}
demo here
the easiest thing to do would be to loop through your second array and assign it's value to the first based on the key...
$arr1=array ("one","two","three","four","five");
$arr2=array( 2=>"cat",4="dog");
foreach ($arr2 as $key=>$value){
if (!empty($value)){
$arr1[$key]=$value;
}
}
I'm having a strange problem while building arrays. I start off with an array that looks like this:
Array (
[0] => Array (
[tag_id] => 19
[tag_translation_id] => 12
[fk_language_id] => 1
[fk_tag_id] => 19
[tag_name] => test
)
[1] => Array (
[tag_id] => 20
[tag_translation_id] => 14
[fk_language_id] => 1
[fk_tag_id] => 20
[tag_name] => testa
)
[2] => Array (
[tag_id] => 20
[tag_translation_id] => 15
[fk_language_id] => 3
[fk_tag_id] => 20
[tag_name] => fdfda
)
)
What I want to do is merge each result with the same tag_id into a single array. This works:
$tags = array();
foreach($results->as_array() as $key=>$result)
{
if(!in_array($result['tag_id'], $tags))
{
$tags[$result['tag_id']] = array();
}
}
foreach($results->as_array() as $result)
{
array_push($tags[$result['tag_id']], array($result['fk_language_id'] , $result['tag_name']));
}
Here is the intended result:
Array (
[19] => Array (
[0] => Array (
[0] => 1
[1] => test
)
)
[20] => Array (
[0] => Array (
[0] => 1
[1] => testa
)
[1] => Array (
[0] => 3
[1] => fdfda
)
)
)
However, I've got two loops here, and I know this isn't ideal. Why do THESE not work??
$tags = array();
foreach($results->as_array() as $key=>$result)
{
$tags[$result['tag_id']] .= array($result['fk_language_id'] , $result['tag_name']);
}
With this example I get two empty arrays...
Array ( [19] => Array [20] => ArrayArray )
Or even...
$tags = array();
foreach($results->as_array() as $key=>$result)
{
if(!in_array($result['tag_id'], $tags))
{
$tags[$result['tag_id']] = array();
}
array_push($tags[$result['tag_id']], array($result['fk_language_id'] , $result['tag_name']));
}
Which for some reason overwrites the first value of the second array with the second value of the second array.
Array (
[19] => Array (
[0] => Array (
[0] => 1
[1] => test
)
)
[20] => Array (
[0] => Array (
[0] => 3
[1] => fdfda
)
)
)
What am I doing wrong in the second 2 examples?
To answer your question, your second method fails because you're using the incorrect .= operator. Your third method fails because your !in_array check is always false (it checks whether the value is in the array, not whether the key is set) and overwrites the array each iteration. You only really need this (as mentioned by others, in pseudo-code):
$result = array();
foreach ($array as $values) {
$result[$values['key']][] = array($values['foo'], $values['bar']);
}
The .= operator is string concatenation. Arrays are merged with +=.
If I understand the issue correctly, the code should go like this:
$tags = array();
foreach ($results as $result)
$tags[$result['tag_id']][] = array($result['fk_language_id'], $result['tag_name']);
$tags = array();
foreach($results->as_array() as $key=>$result)
{
$tags[$result['tag_id']] .= array($result['fk_language_id'] , $result['tag_name']);
}
you cannot add a value to an array with the .= (dot equal) operator.
why are you doing $results->as_array() ????
do simply:
foreach($results as $key=>$result) {
Instead of using .= try using []
$tags = array();
foreach ($results as $result)
{
if(!isset($tags[$result['tag_id']]))
$tags[$result['tag_id']] = array();
$tags[$result['tag_id']][] = array($result['fk_language_id'], result['tag_name']);
}
.= is to concatinate a string
+= is to concatinate a number
[] is to concatinate to an array
Hope this helps?
Edit: Noticed that it "might" fail if the tag_id doesn't already exist in the array, so it might be worth just checking first and setting it to an array just in case.