How to rename anonymous keys in multidimensional array - php

array:4 [▼
0 => array:2 [▼
0 => "chrysanthemum.jpg"
1 => "http://site.loc/1"
]
1 => array:2 [▼
0 => "desert.jpg"
1 => "http://site.loc/2"
]
2 => array:2 [▼
0 => "hydrangeas.jpg"
1 => "http://site.loc/3"
]
3 => array:2 [▼
0 => "jellyfish.jpg"
1 => "http://site.loc/4"
]
]
How to rename 0 to ['img'] and 1 to ['link'] in each array?
Trying this:
foreach($data as $array){
$array['img']=$array[0];
unset($array[0]);
$array['link']=$array[1];
unset($array[1]);
}
but it doesn't work :c
Does php have a function for this task?

You have two ways to do that.
The first, only put the & in the parameter:
foreach($data as &$array){
$array['img']=$array[0];
unset($array[0]);
$array['link']=$array[1];
unset($array[1]);
}
This will allow change the $array.
Another way is using the array_map:
$data = array_map(function($data) {
return [
'img' => $data['0'],
'link' => $data['1']
];
}, $data);
Response:
array(4) {
[0]=>
array(2) {
["img"]=>
string(17) "chrysanthemum.jpg"
["link"]=>
string(17) "http://site.loc/1"
}
[1]=>
array(2) {
["img"]=>
string(10) "desert.jpg"
["link"]=>
string(17) "http://site.loc/2"
}
[2]=>
array(2) {
["img"]=>
string(14) "hydrangeas.jpg"
["link"]=>
string(17) "http://site.loc/3"
}
[3]=>
array(2) {
["img"]=>
string(13) "jellyfish.jpg"
["link"]=>
string(17) "http://site.loc/4"
}
}
In both cases.

You need to access it via reference, right now you're just changing a copy of the data and not changing the data at all.
foreach($data as &$array){
$array['img'] = $array[0];
$array['link'] = $array[1];
unset($array[0], $array[1]);
}

Related

Merge 2d arrays with same index value

How can I merge one array inside another 2d array based on a unique value that is shared on both 2d array?
Arrays:
$arr1 = [
"First" =>[
"Name" => "John",
"Id" => 123
],
"Second" =>[
"Name" => "Peter",
"Id" => 45
]
];
$arr2 = [
"First" =>[
"Age" => 34,
"Id" => 123
],
"Second" =>[
"Age" => 24,
"Id" => 45
]
];
$n = array_merge($arr1, $arr2);
Current output when var_dump $n:
array(2) {
["First"]=>
array(2) {
["Age"]=>
int(34)
["Id"]=>
int(123)
}
["Second"]=>
array(2) {
["Age"]=>
int(24)
["Id"]=>
int(45)
}
}
Desired output:
array(2) {
["First"]=>
array(2) {
["Name"]=>
String("John")
["Age"]=>
int(34)
["Id"]=>
int(123)
}
["Second"]=>
array(2) {
["Name"]=>
String("Peter")
["Age"]=>
int(24)
["Id"]=>
int(45)
}
}
Ofcourse just by merging the two arrays wont fix my issue, but i was just wondering what approach I should take to do this.
Assuming this structure of your arrays, you can use array_replace_recursive.
$n = array_replace_recursive($arr1, $arr2);
Fiddle: https://3v4l.org/IPGsl
Some people can say that you can use array_merge_recursive, but no. As you have same key (Id) in both arrays, resulting array will have not the structure you expect. But in case you have different keys in both arrays - array_merge_recursive is an option too.

Restructure array data by chunking, transposing, and merging

I have array mentioned below, I will have value always multiple of 3.
$xyz = [
["name" => "abc"],
["name" => "snds"],
["name" => ""),
["number"=> "452"],
["number" => "845120"],
["number" => "84514513200"],
["email" => "ddddf"],
["email" => "dkskns"],
["email" => "kjnksdnkds"]
];
but this is not the proper format for me to perform further operations, so I want this array like mentioned below.
$abc = [
[
"name" => "abc",
"number" => '452',
"email" => "ddddf"
],
[
"name" => "snds",
"number" => "845120",
"email" => "dkskns"
],
[
"name" => "",
"number" => "84514513200",
"email" => "kjnksdnkds"
]
];
note: the array length is dynamic but it will always be multiple of 3
One possibility could be to use the modulo % operator.
In the foreach the value is an array and you could use array_keys to get the key and reset to get the value of the first array element.
$result = [];
$count = 0;
foreach ($xyz as $value) {
if ($count%3 === 0) {
$count = 0;
}
$result[$count][array_keys($value)[0]] = reset($value);
$count++;
}
Demo
That will give you:
array(3) {
[0]=>
array(3) {
["name"]=>
string(3) "abc"
["number"]=>
string(3) "452"
["email"]=>
string(5) "ddddf"
}
[1]=>
array(3) {
["name"]=>
string(4) "snds"
["number"]=>
string(6) "845120"
["email"]=>
string(6) "dkskns"
}
[2]=>
array(3) {
["name"]=>
string(0) ""
["number"]=>
string(11) "84514513200"
["email"]=>
string(10) "kjnksdnkds"
}
}
This will do:
$result = array_map('array_merge', ...array_chunk($xyz, count($xyz) / 3));

multidimensional array to simple array

I have an array like this
array(5) {
[0]=> array(2) { [0]=> string(5) "REFER" [1]=> string(12) "Não Sócios" }
[1]=> array(2) { [0]=> string(5) "REFER" [1]=> string(12) "Não Sócios" }
[2]=> array(2) { [0]=> string(5) "REFER" [1]=> string(12) "Não Sócios" }
[3]=> array(2) { [0]=> string(5) "REFER" [1]=> string(12) "Não Sócios" }
[4]=> array(2) { [0]=> string(5) "REFER" [1]=> string(12) "Não Sócios" }
}
and want to transform this array into an array like this
array("REFER, Não Sócios", "REFER, Não Sócios", "REFER, Não Sócios", "REFER, Não Sócios", "REFER, Não Sócios");
is that possible? if so, how can i do it?
thanks in advance
Yes. Assuming that array is called $refer -
$new_refer = array_map(function($val) {
return implode(', ', $val);
}, $refer);
Using parray_map you iterate over the elements and construct a new array with values returned from the callback function. Inside that function i'm using implode to combine the values of each element (which is an array in itself) and glue them with ', '.
You can do it with array_map for example:
$r = array_map(function($v) { return $v[0] . ', ' . $v[1]; }, $source_array);
here's a way you can do it:
$a = [
[ 0 => "REFER", 1 => "Nao Socios" ] ,
[ 0 => "REFER", 1 => "Nao Socios" ] ,
[ 0 => "REFER", 1 => "Nao Socios" ] ,
[ 0 => "REFER", 1 => "Nao Socios" ] ,
[ 0 => "REFER", 1 => "Nao Socios" ]
];
$res = [];
foreach ($a as $k => $v) {
$res[] = $v[0];
$res[] = $v[1];
}
var_dump($res);

PHP: manipulate array making value as key recursively

I got this array:
array:2 [▼
0 => array:1 [▼
0 => array:7 [▼
"id" => "1"
"producer" => "Samsung"
"model" => "LE22B541C4W"
"category" => "1"
"production_date" => "2009-05-08"
"status" => "Discontinued"
"type" => "LCD"
]
]
1 => array:1 [▼
0 => array:7 [▼
"id" => "2"
"producer" => "Samsung"
"model" => "P24FHD"
"category" => "1"
"production_date" => "0000-00-00"
"status" => "Discontinued"
"type" => "LCD"
]
]
[...]
]
I would like to take the "ID" value of each array and make as primary key and remove the useless keys like this
array:2 [
1 => array:7 [
"id" => "1"
"producer" => "Samsung"
"model" => "LE22B541C4W"
"category" => "1"
"production_date" => "2009-05-08"
"status" => "Discontinued"
"type" => "LCD"
]
2 => array:7 [
[...]
By now I'm just populate the array using this simple query and a for loop:
foreach ($compatibility as $compElement) {
$sql = "SELECT * FROM product WHERE ID = '$compElement';";
$em = $this->getDoctrine()->getManager();
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute();
$thisElement = $stmt->fetchAll();
$compArray[] = $thisElement;
}
You can do something like this if you don't want to change how you populate your array:
$result = call_user_func_array(
'array_merge_recursive',
$array
);
Output
array(2) {
[0]=>
array(7) {
["id"]=>
string(1) "1"
["producer"]=>
string(7) "Samsung"
["model"]=>
string(11) "LE22B541C4W"
["category"]=>
string(1) "1"
["production_date"]=>
string(10) "2009-05-08"
["status"]=>
string(12) "Discontinued"
["type"]=>
string(3) "LCD"
}
[1]=>
array(7) {
["id"]=>
string(1) "2"
["producer"]=>
string(7) "Samsung"
["model"]=>
string(6) "P24FHD"
["category"]=>
string(1) "1"
["production_date"]=>
string(10) "0000-00-00"
["status"]=>
string(12) "Discontinued"
["type"]=>
string(3) "LCD"
}
}

Build array from specific indices in a multidimensional array

How would I filter out the index of zero which contains the name of the rows being returned from a MySQL query, and then put the results back into a array like the one shown below.
Desired example array:
array:1 [
0 => array:10 [
0 => array:2 [
0 => "2016-01-06"
1 => 10
]
1 => array:2 [
0 => "2016-01-12"
1 => 15
]
]
]
Array that's returned from MySQL query:
array:1 [
0 => array:10 [
0 => array:2 [
0 => "price_1"
1 => 10
]
1 => array:2 [
0 => "day_1"
1 => "2016-01-06"
]
2 => array:2 [
0 => "price_2"
1 => 15
]
3 => array:2 [
0 => "day_2"
1 => "2016-01-12"
]
]
]
You could do something like (assuming $array is your input array with the MySQL results, and $output is our transformed result array):
<?php
$output = array_map(function($value) {
return [$value[1][1], $value[0][1]];
}, $array);
Here's an example using your input:
php > var_dump($array);
array(1) {
[0]=>
array(4) {
[0]=>
array(2) {
[0]=>
string(7) "price_1"
[1]=>
int(10)
}
[1]=>
array(2) {
[0]=>
string(5) "day_1"
[1]=>
string(10) "2016-01-06"
}
[2]=>
array(2) {
[0]=>
string(7) "price_2"
[1]=>
int(15)
}
[3]=>
array(2) {
[0]=>
string(5) "day_2"
[1]=>
string(10) "2016-01-12"
}
}
}
php > $output = array_map(function($value) { return [$value[1][1], $value[0][1]]; }, $array);
php > var_dump($output); array(1) {
[0]=>
array(2) {
[0]=>
string(10) "2016-01-06"
[1]=>
int(10)
}
}
php >

Categories