Change indexed Array to Associative Array PHP - php

I have an array from json_decode. And i want to reformat it.
this is my array format.
["Schedule"]=>array(1) {
["Origin"]=>
string(3) "LAX"
["Destination"]=>
string(2) "CGK"
["DateMarket"]=>
array(2) {
["DepartDate"]=>
string(19) "2015-02-01T00:00:00"
["Journeys"]=>
array(6) {
[0]=>
array(6) {
[0]=>
string(2) "3210"
[1]=>
string(14) "Plane Name"
[2]=>
string(8) "20150201"
[3]=>
string(8) "20150201"
[4]=>
string(4) "0815"
[5]=>
string(4) "1524"
}
}
}
And i want change the indexed array to associative with foreach function.
And here is my PHP code
foreach ($response->Schedule['DateMarket']['Journeys'] as $key=>$value) {
$value->Name= $value[1];
}
But i got an error "Attempt to assign property of non-object on line xXx..
My Question is, how to insert a new associative array to indexed array like the example that i've provide.
UPDATE : I've tried this solution
foreach ($response->Schedule['DateMarket']['Journeys'] as $key=>$value) {
$value['Name']=$value[1];
}
But my array format still the same, no error.

In this line:
$value->Name= $value[1];
You expect $value to be both object ($value->Name) and array ($value[1]).
Change it to something like:
foreach ($response->Schedule['DateMarket']['Journeys'] as $key=>$value) {
$response->Schedule['DateMarket']['Journeys'][$key]['Name'] = $value[1];
}
Or even better, without foreach:
$keys = array(
0 => 'Id',
1 => 'Name',
2 => 'DateStart',
3 => 'DateEnd',
4 => 'HourStart',
5 => 'HourEnd',
);
$values = $response->Schedule['DateMarket']['Journeys'];
$response->Schedule['DateMarket']['Journeys'] = array_combine( $keys , $values );
Array_combine makes an array using keys from one input and alues from the other.
Docs: http://php.net/manual/en/function.array-combine.php

Try this:
foreach ($response->Schedule['DateMarket']['Journeys'] as $key=>$value) {
$value['Name'] = $value[1];
}

You want to create new array index, but try to create new object.
foreach ($response->Schedule['DateMarket']['Journeys'] as $key => $value) {
$value['Name'] = $value[1];
}

Related

How can I flatten a Multidimensional array into a string?

Ive researched this but im coming up blank, Im generating an array of tests from a database like so:
$descriptions = array();
foreach ($tests as $value) {
array_push($descriptions, ['name' => $value['name']]);
}
I'm getting the desired out put but i'm getting a Multidimensional array of an array with '[64]' arrays inside '$descriptions', I need to convert this array so I get the following output:
'name' => $value1, 'name' => $value2, etc etc for all results,
I've tried implode, array_merge etc but the closest I've got is a flat array with only my last test: [name] => Zika can anyone point me in the right direction? cheers
You can't have duplicate array keys. But you can pass an array in like so:
<?php
$descriptions = array();
$tests = array(
'Zika', 'SARS', 'AIDS', 'Mad Cow Disease', 'Bird Flu', 'Zombie Infection',
);
foreach ($tests as $value) {
$descriptions[] = array('name' => $value);
}
var_dump($descriptions);
Which gives you :
array(6) { [0]=> array(1) { ["name"]=> string(4) "Zika" } [1]=> array(1) { ["name"]=> string(4) "SARS" } [2]=> array(1) { ["name"]=> string(4) "AIDS" } [3]=> array(1) { ["name"]=> string(15) "Mad Cow Disease" } [4]=> array(1) { ["name"]=> string(8) "Bird Flu" } [5]=> array(1) { ["name"]=> string(16) "Zombie Infection" } }
So you could foreach ($descriptions as $desc) and echo $desc['name']';
Have a look here: https://3v4l.org/pWSC6
If you just want a string, try this:
<?php
$descriptions = '';
$tests = array(
'Zika', 'SARS', 'AIDS', 'Mad Cow Disease', 'Bird Flu', 'Zombie Infection',
);
foreach ($tests as $value) {
$descriptions .= 'name => '.$value.', ';
}
$descriptions = substr($descriptions, 0, -2); // lose the last comma
echo $descriptions;
Which will output:
name => Zika, name => SARS, name => AIDS, name => Mad Cow Disease, name => Bird Flu, name => Zombie Infection
See it here https://3v4l.org/OFGF4

How i can take first array from array

I have an array containing two arrays. When I write var_dump($array):
array(7) {
["Article"]=>
array(1) {
[0]=>
string(8) "39-746У"
}
["Visible"]=>
array(1) {
[0]=>
string(1) "1"
}
}
array(7) {
["Article"]=>
array(1) {
[0]=>
string(6) "12-003"
}
["Visible"]=>
array(1) {
[0]=>
string(1) "1"
}
}
When I write var_dump($array[0]) i get NULL.
I want to change Visible in the second array, but it change in two arrays
Real code:
$sql2="select tblCurrencies.name as name,Price,tblArticleInfo.Name as Name,ArticleID,CategoryID,Article,Visible from tblArticles,tblArticleInfo,tblCurrencies where tblArticleInfo.ArticleID=tblArticles.Id and tblArticles.Id='{$tovar_id}' and tblArticles.currencyID=tblCurrencies.id";
$Array2=query_result_as_rows($sql2,$conn);
You have two different kinds of array here, an associative array, with key-value pairs, and a non-associative array, indexed by number.
Associative array:
$a_array = array(
"Article" => "foo",
"Visible" => " bar",
);
Access data in an associative array:
echo $a_array['Article'];
// prints 'foo'
Iterate through an associative array:
foreach ($a_array as $key => $value) {
echo "$key, $value; ";
}
// prints 'Article, foo; Visible, bar'
//
A numerically-indexed array:
$num_array = ('pip', 'pap', 'pop');
Access items in a numerically-indexed array:
echo $num_array[0] . ", " . $num_array[2];
// prints 'pip, pop'
Iterate through the array:
foreach ($num_array as $num) {
echo "$num! ";
}
// prints "pip! pap! pop! "
You have an associative array with a numerically-indexed array inside it:
$array = array(
'Article' => array( '39-746У' ),
'Visible' => array( '1' )
);
var_dump of $array:
array(2) {
["Article"]=>
array(1) {
[0]=>
string(8) "39-746У"
}
["Visible"]=>
array(1) {
[0]=>
string(1) "1"
}
}
To access data, you need to combine the two methods:
echo $array['Article'][0];
// prints "39-746У"
To iterate through the arrays:
foreach ($array as $key => $value) { // this is the outer associative array
echo "outer array key: $key...\n"; // $value is the inner array
foreach ($value as $v) { // $value is a numerically-indexed array
echo "inner array item: $v\n";
}
}
Output:
outer array key: Article
inner array item: 39-746У
outer array key: Visible
inner array item: 1
Here's a workaround:
$array = array(...);
$array_keys = array_keys($array);
$array_first_key = $array_keys[0];
var_dump($array[$array_first_key]);
also:
var_dump(array_shift($array));
With php 5.4+
array_values($array)[0];

Convert array in array to string

I wonder if there's easy way to convert array which is in another array to string and keep it in that array ? The array which is inside array always consists of only 1 key. This is array that I have now:
array(6) {
["miestas"]=>
string(2) "CC"
["checkbox"]=>
array(1) {
[0]=>
string(1) "1"
}
["kiekis"]=>
string(5) "Three"
}
And this is the result what I want to get:
array(6) {
["miestas"]=>
string(2) "CC"
["checkbox"]=>
string(1) "1"
["kiekis"]=>
string(5) "Three"
}
Read this: http://php.net/array
Use this: $array['checkbox'] = $array['checkbox'][0];
You can type cast the value
$data['checkbox'] = (string) $data['checkbox'];
array_replace
$replacement = array('checkbox' => 1);
$outputYouWant = array_replace($yourArray, $replacement);
print_r($outputYouWant);
Loops through the input array and checks if value is an array using is_array function. Pushes value array's value at index zero if an array otherwise pushes value to the result array.
$input = array('miestas' => 'CC', 'checkbox' => array("1"), 'kiekis' => 'Three');
$result = array();
foreach($input as $key=>$value) {
$result[$key] = is_array($value) ? $value[0] : $value;
}
// var_dump($result);

how to sort multi dimensional array with object? [duplicate]

This question already has answers here:
How do I sort a multidimensional array by one of the fields of the inner array in PHP? [duplicate]
(8 answers)
Closed last year.
Question: how to sort multi dimensional array with object?
Status : I've an array as following.
array(3) {
[0]=>
object(Photo_model)#25 (5) {
["id"]=>
int(5)
["file_name"]=>
string(36) "A49361605AE049D687CDC3FEAF7D3236.jpg"
["user_id"]=>
int(1)
["challenge_id"]=>
string(1) "2"
["score"]=>
int(19)
}
[1]=>
object(Photo_model)#28 (5) {
["id"]=>
int(2)
["file_name"]=>
string(36) "A49361605AE049D687CDC3FEAF7D3236.jpg"
["user_id"]=>
int(1)
["challenge_id"]=>
string(1) "2"
["score"]=>
int(10)
}
[2]=>
object(Photo_model)#29 (5) {
["id"]=>
int(3)
["file_name"]=>
string(36) "A49361605AE049D687CDC3FEAF7D3236.jpg"
["user_id"]=>
int(1)
["challenge_id"]=>
string(1) "2"
["score"]=>
int(15)
}
}
I tried to sort above array by score. I created a function as follow.
aarsort (&$array, 'score');
function aarsort (&$array, $key) {
$sorter=array();
$ret=array();
reset($array);
foreach ($array as $ii => $va) {
$sorter[$ii]=$va[$key];
}
arsort($sorter);
foreach ($sorter as $ii => $va) {
$ret[$ii]=$array[$ii];
}
$array=$ret;
}
But it is not working. How can I sort the multidimensional array by key (score)?
result should be by id => 5,3,2
Your array is only 1 dimensional, and there is an object in each array item.
After all, to sort a 1D array consisting of objects, and sort by a certain property of the objects, use usort
usort($array, function($a, $b) {
return $a->score - $b->score
});
To get id => 5, 3, 2 from above, just loop through the array from the above code and access the property to get it
$ids = array();
foreach ($array as $item) {
$ids[] = $item->id;
}
var_dump($ids);
And I am not sure if the order is right. If it turns out to be reverse order, just negate the result of the closure in the usort function.
It just example.
//$newarray for store all array id
//$array is your previous array . You just enter your all index whose key id store in new array
$newarray = array();
foreach($array as $obj => $id)
{
$newarray[] = $id[$key];
}
array_multisort($newarray,SORT_ASC,$array);
I've done this problem by php.net
// Obtain a list of columns
foreach ($array as $key => $row) {
$_score[$key] = $row->score;
}
// Sort the data with volume descending, edition ascending
// Add $data as the last parameter, to sort by the common key
array_multisort($_score, SORT_DESC, $array);

target numeric keys only in array

I have an array with 2 kinds of keys, strings and integers. I want to do foreach() on this array and want to do it for numeric keys only. What is the most elegant way of doing it?
Here's a complicated method using array_filter() to return the numeric keys then iterate over them.
// $input_array is your original array with numeric and string keys
// array_filter() returns an array of the numeric keys
// Use an anonymous function if logic beyond a simple built-in filtering function is needed
$numerickeys = array_filter(array_keys($input_array), function($k) {return is_int($k);});
// But in this simple case where the filter function is a plain
// built-in function requiring one argument, it can be passed as a string:
// Really, this is all that's needed:
$numerickeys = array_filter(array_keys($input_array), 'is_int');
foreach ($numerickeys as $key) {
// do something with $input_array[$key']
}
It's much easier though to just foreach over everything:
foreach ($input_array as $key => $val) {
if (is_int($key)) {
// do stuff
}
}
Edit Misread original post and thought I saw "numeric" rather than "integer" keys. Updated to use is_int() rather than is_numeric().
foreach($array as $key => $val) {
if(!is_int($key))
continue;
// rest of the logic
}
This one-liner returns a new array with the values and its numeric keys:
$new_array = array_filter($my_array, 'is_int', ARRAY_FILTER_USE_KEY);
so if we have this:
array(
'fruit' => 'banana'
1 => 'papaya'
)
..we get this:
array(
1 => 'papaya'
)
Using array_filter you must aware if you have value that similar as FALSE.
This is my solution:
function filterArrayKeyInteger(Array $array) {
$integer = array_filter($array, function ($key) {
if ($key === 0 || is_int($key)) {
return true;
}
}, ARRAY_FILTER_USE_KEY);
return array_intersect_key($array, $integer);
}
$a = [0, false, 'aa','bb', 'cc', 'dd' => 'dd', '9.9' => 9.9];
$b = filterArrayKeyInteger($a);
Result of vardump
var_dump(a): array(7) {
[0]=>
int(0)
[1]=>
bool(false)
[2]=>
string(2) "aa"
[3]=>
string(2) "bb"
[4]=>
string(2) "cc"
["dd"]=>
string(2) "dd"
["9.9"]=>
float(9.9)
}
var_dump(b): array(5) {
[0]=>
int(0)
[1]=>
bool(false)
[2]=>
string(2) "aa"
[3]=>
string(2) "bb"
[4]=>
string(2) "cc"
}

Categories