How to change value of one element to key in array? - php

How can I make value of one element into key in the same array
from this
[0]=>
array(2) {
["name"]=>
string(7) "segment"
["value"]=>
string(9) "Name Test"
}
to this
["segment"]=> "Name Test"

Try and run each item through a function or foreach loop assigning it as you want.
$res = array();
foreach($data as $item)
{
$res[$item['name']] = $item['value'];
}
Or through a function such as array_walk
$res = array();
array_walk($data, function($item, $key) use (&$res) {
$res[$item['name']] = $item['value'];
});

Simplifying (if you have one row indexed as '0'):
$array = array('0' => array('name'=>'segment'
'value'=>'Name Test'));
$new_array = array();
$new_array[$array[0]['name']] = $array[0]['value'];
print_r($new_array);

Related

Re-arranging and combining an array

I'm having an issue when I dump the array below. This dumps several arrays. Some are 2 some are 3, which complicates it even more. Basically what I want I put below. I have tried array_push, array_combine, array_merge, several different ways including $array[$param] = $insertValue and I'm stuck. I am open to creating a brand new array too.
Please note not all arrays are counts of 3 but always return at least 1.
Original array:
array(3) {
[0]=>
array(2) {
["contact_id"]=>
string(9) "CONTACTID"
["contact_id_content"]=>
string(19) "123456789123456"
}
[1]=>
array(2) {
["sm_owner"]=>
string(9) "SMOWNERID"
["sm_owner_content"]=>
string(19) "123456798452"
}
[2]=>
array(2) {
["contact_owner"]=>
string(13) "Contact Owner"
["contact_owner_content"]=>
string(16) "Jane Doe"
}
Array desired:
array(3) {
[0]=>
array(6) {
["contact_id"]=>
string(9) "CONTACTID"
["contact_id_content"]=>
string(19) "123456789123456"
["sm_owner"]=>
string(9) "SMOWNERID"
["sm_owner_content"]=>
string(19) "123456798452"
["contact_owner"]=>
string(13) "Contact Owner"
["contact_owner_content"]=>
string(16) "Jane Doe"
}
try this code:
$NewArray = array();
foreach($OriginalArray as $value) {
$NewArray[] = array_merge($value,$NewArray);
}
or you can use array_merge_recursive
let $result = [];
foreach ($yourarray as $key => $value) {
$result = $value;
}
var_dump($result);
Here you go: How to Flatten a Multidimensional Array? – Barmar 23 mins ago
function flatten($array)
{
return array_reduce($array, function($acc, $item){
return array_merge($acc, is_array($item) ? flatten($item) : [$item]);
}, []);
}
// loop the individual fields
for ($i=0; $i<count($row_data); $i++) {
$newArray = flatten([$i => $response_row]);
}
Try something like this:
function flatten(array $array) : array
{
$newArray = [];
foreach ($array as $subArray) {
foreach ($subArray as $key => $value) {
$newArray[$key] = $value;
}
}
return $newArray;
}

Php array value to keys

Hi let's say I have this array
array(2) {
[0]=>
string(9) "name|a-z+"
[1]=>
string(7) "id|0-9+"
}
Now I want a new array (or the same if possible) to be like this:
array(2) {
[name]=>
string(4) "a-z+"
[id]=>
string(4) "0-9+"
}
I think the solution implies explode and array_combine, but I am not good enough, can someone help me?
Thanks in advance.
function convert_my_array($arr){
$out = array();
foreach($arr as $obj){
$data = explode("|", $obj);
$out[$data[0]] = $data[1];
}
return $out;
}
Using the original array called $array here, loop through it set the values to what you want.
$newarray = array();
foreach ($array as $key=>$val) {
list($one, $two) = explode('|', $val);
$newarray[$one] = $two;
}

Changes to array of JSON objects based on other array

I have an array of JSON objects that look like this:
{"id":1,"place":2,"pic_name":"aaa.jpg"}
My PHP file receives a simple array like:
["4","3","1","2","5"]
These numbers correspond to the place value in my JSON object. Now I need to compare the place of each element in the secont array with the value of ID in the JSON object and if the match I have to replace the value of PLACE with the element from the array.
I am having problems doing the comparison. Any guidelines? What I come up with:
foreach($ids as $index=>$id) { //the array
$id = (int) $id;
foreach ($obj as $key=>$value) { //the JSON objects
foreach ($value as $k=>$v){
if ($id != '' && array_search($index, array_keys($ids)) == $value[$k]['id']) {
$value[$k]['place'] = $id;
file_put_contents($file, json_encode($ids));
} else { print "nope";}
} } }
That will be:
$array = [
'{"id":1,"place":2,"pic_name":"aaa.jpg"}',
'{"id":2,"place":5,"pic_name":"aab.jpg"}',
'{"id":3,"place":1,"pic_name":"aba.jpg"}',
'{"id":4,"place":3,"pic_name":"baa.jpg"}',
'{"id":5,"place":4,"pic_name":"abb.jpg"}'
];
$places = ["4","3","1","2","5"];
$array = array_map(function($item)
{
return json_decode($item, 1);
}, $array);
foreach($array as $i=>$jsonData)
{
if(false!==($place=array_search($jsonData['id'], $places)))
{
$array[$i]['place'] = $place+1;
}
}
$array = array_map('json_encode', $array);
//var_dump($array);
-with output like:
array(5) {
[0]=>
string(39) "{"id":1,"place":3,"pic_name":"aaa.jpg"}"
[1]=>
string(39) "{"id":2,"place":4,"pic_name":"aab.jpg"}"
[2]=>
string(39) "{"id":3,"place":2,"pic_name":"aba.jpg"}"
[3]=>
string(39) "{"id":4,"place":1,"pic_name":"baa.jpg"}"
[4]=>
string(39) "{"id":5,"place":5,"pic_name":"abb.jpg"}"
}

How to get all keys out of associative array in php

I have an associative array in php. When I am doing a die on it, then I am getting proper values as follows:
array(1) { [0]=> array(1) { [123]=> string(5) "Hello" }}
But when I am trying extract out keys of this array into an new array, then I am not able to get keys out:
$uniqueIds = array_keys($myAssociativeArray);
die(var_dump($uniqueIds));
int(0) array(1) { [0]=> int(0) }
Can any one tell me what I am doing wrong here? I want to get all the keys out of my associative array. And for this, I am referring to thread: php: how to get associative array key from numeric index?
$uniqueIds = array_keys($myAssociativeArray[0]);
<?php
function multiarray_keys($ar) {
foreach($ar as $k => $v) {
$keys[] = $k;
if (is_array($ar[$k]))
$keys = array_merge($keys, multiarray_keys($ar[$k]));
}
return $keys;
}
$result = multiarray_keys($myAssociativeArray);
var_dump($result);
?>
The following recursively gets all the keys in an associative array
function getArrayKeysFlat($array) {
if(!isset($keys) || !is_array($keys)) {
$keys = array();
}
foreach($array as $key => $value) {
$keys[] = $key;
if(is_array($value)) {
$keys = array_merge($keys,getArrayKeysFlat($value));
}
}
return $keys;
}

Create string to put in an IN statement from an array of arrays

I have an array of arrays that look like this:
array(40) {
[0]=>
array(2) {
["id"]=>
string(2) "ta"
["size"]=>
int(2)
[1]=>
array(2) {
["id"]=>
string(2) "tq"
["size"]=>
int(4)
....
I want to be able to get all the sizes in a way that I can do a query like this:
IN (2,4)
so... For each array, get the size key: IN (size,size,size...)
Thanks!
You could do something like this:-
$sizes = implode(',', array_map(function($v) { return $v['size']; }, $array));
Then just pass $sizes to your IN query
edit
In response to your comment below, you can use array_unique to remove duplicate sizes, eg:
$sizes = implode(',', array_unique(array_map(function($v) { return $v['size']; }, $array)));
Here you go:
$a = array("id"=>"ta","size"=>2);
$b = array("id"=>"tq","size"=>4);
$c = array($a,$b);
$in = array();
foreach ($c as $key=>$value) {
if(array_key_exists("size", $value)){
$in[] = $value["size"];
}
}
echo implode(",", $in);
$sizes = array();
foreach($array as $value) {
$sizes[] = $value['size'];
}
$query = implode(',', $sizes);
query ..." IN ($query) "..

Categories